对于提供TypeError的空对象:无法将未定义或null转换为对象

问题描述 投票:0回答:2

嗯,我知道这是一个非常普遍的问题,但是我试图找到解决方案,但是还没有运气。所以这是问题陈述:

由于某种情况,我的对象没有值,并且为空{},当我尝试使用Object.keys(ambassador).lengthObject.entries(ambassador).length检查该对象的长度时,出现了错误

TypeError:无法将未定义或null转换为对象。

代码示例:

const ambassador = Array.isArray(ambassadors) 
        ? ambassadors.find((item) => {
                return item.affiliate_id === affiliate.tracking_id;
            })
        : {};

console.log(ambassador == null); //false
console.log(typeof(ambassador)); // Object
console.log(Object.keys(ambassador).length > 0 ); //TypeError: Cannot convert undefined or null to object.
javascript arrays reactjs object is-empty
2个回答
0
投票

As mdn says

null值表示故意缺少任何对象值。它是JavaScript的primitive values之一,被视为虚假布尔运算

在读取键之前尝试检查您的对象是否不是null

let ambassador = null;
console.log(ambassador == null); //false
console.log(typeof(ambassador)); // Object
if (ambassador)
    console.log(Object.keys(ambassador).length > 0 );

示例:

let ambassador = null;
console.log(ambassador == null); //false
console.log(typeof(ambassador)); // Object
if (ambassador)
    console.log(Object.keys(ambassador).length > 0 );

UPDATE:

如果let ambassador = {};,则abmassadortruthy,因此您可以检查对象的键:

let ambassador = {};
console.log(ambassador == null); //false
console.log(typeof(ambassador)); // Object
if (ambassador)
    console.log(`ambassador`, Object.keys(ambassador).length > 0 );

As mdn says

在JavaScript中,真实值是当在布尔上下文中遇到。除非所有价值观都是真实的被定义为伪造(即,除了false,0、0n,“”,null,未定义和NaN)。

JavaScript中真实值的示例(在布尔上下文中将其强制为true,并因此执行if块):

if (true)
if ({})
if ([])
if (42)
if ("0")

0
投票

所以,我从Kireeti Ganisetti的评论中得到了解决方案,他建议使用LOADASH,它很有效:)

检查Javascript中对象是否为空-React:

import _ from 'lodash';
_.isEmpty(ambassador)
© www.soinside.com 2019 - 2024. All rights reserved.