我有一个从API接收的对象。现在我想显示对象中的一个特定值,但是如果该值为null,则使用get()应该为空。
考虑如下对象:
const person = {
firstName:"John",
lastName:"Doe",
petName: null,
age:50,
eyeColor:"blue"};
假设我仅在收到来自API的对象时才显示Pet Name的值。但是我不想显示'NULL',相反,它应该是空的。
<Box>{`Pet Name: ${ person ? get(person, 'petName') : '' }`}</Box>
输出=>宠物名称:空
相反,希望输出为=>宠物名称:(如果为空,则为空,否则为值)
发布于 2021-07-12 08:03:29
您可以使用nullish coalescing
<Box>{`Pet Name: ${ person ? get(person, 'petName') ?? '' : '' }`}</Box>
发布于 2021-07-12 07:52:40
这个可以解决这个问题。再添加一个条件语句。
<Box>{`Pet Name: ${ person ? get(person, 'petName') ? get(person, 'petName'):'' : '' }`}</Box>
发布于 2021-07-12 07:55:06
javascript对象是真实的,因此您的代码总是在三元组中运行get()。要检查空对象,请尝试:
<Box>{`Pet Name: ${ ( person && Object.keys(person).length !==0 ) ? get(person, 'petName') : '' }`}</Box>
https://stackoverflow.com/questions/68343736
复制相似问题