For empty object giving the TypeError: Cannot convert undefined or null to object

For empty object giving the TypeError: Cannot convert undefined or null to object

好吧,我知道这是一个非常常见的问题,但我试图找到解决方案,但还没有成功。所以这是问题陈述:

由于某些情况,我的对象没有任何值,它是空的 {},当我尝试使用 Object.keys(ambassador).lengthObject.entries(ambassador).length 检查这个对象的长度时,它是给我错误

TypeError: Cannot convert undefined or null to object.

代码示例:

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.

As mdn says:

The value null represents the intentional absence of any object value. It is one of JavaScript's primitive values and is treated as falsy for boolean operations

在读取键之前尝试检查您的对象是否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 );

更新:

如果 let ambassador = {}; 那么 abmassador 就是 truthy 所以你可以检查对象的键:

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:

In JavaScript, a truthy value is a value that is considered true when encountered in a Boolean context. All values are truthy unless they are defined as falsy (i.e., except for false, 0, 0n, "", null, undefined, and NaN).

JavaScript 中的真值示例(在布尔上下文中将被强制为真,从而执行 if 块):

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

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

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

import _ from 'lodash';
_.isEmpty(ambassador)