[英]For empty object giving the TypeError: Cannot convert undefined or null to object
Well, I know this is would be a very common question but I tried to find the solution but no luck yet.好吧,我知道这将是一个非常常见的问题,但我试图找到解决方案但还没有运气。 So here is the problem statement :所以这里是问题陈述:
Due to some condition, my object is having no values and it is empty {}
and when I try to check the length of this object using Object.keys(ambassador).length
OR Object.entries(ambassador).length
it is giving me the error由于某些条件,我的对象没有值并且它是空的{}
并且当我尝试使用Object.keys(ambassador).length
OR Object.entries(ambassador).length
检查此对象的长度时,它给了我错误
TypeError: Cannot convert undefined or null to object.类型错误:无法将 undefined 或 null 转换为对象。
Code sample:代码示例:
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.
So, I got solution from the comment of Kireeti Ganisetti, He suggested to use LOADASH and it worked :)所以,我从 Kireeti Ganisetti 的评论中得到了解决方案,他建议使用 LOADASH 并且它有效:)
To check if the object is empty in Javascript - React :在 Javascript 中检查对象是否为空 - React:
import _ from 'lodash';
_.isEmpty(ambassador)
The value null represents the intentional absence of any object value.值 null 表示有意缺少任何对象值。 It is one of JavaScript's primitive values and is treated as falsy for boolean operations它是 JavaScript 的原始值之一,对于布尔运算被视为假
Try to check your object whether it is not null
before reading keys:在读取键之前尝试检查您的对象是否为null
:
let ambassador = null;
console.log(ambassador == null); //false
console.log(typeof(ambassador)); // Object
if (ambassador)
console.log(Object.keys(ambassador).length > 0 );
An example:一个例子:
let ambassador = null; console.log(ambassador == null); //false console.log(typeof(ambassador)); // Object if (ambassador) console.log(Object.keys(ambassador).length > 0 );
UPDATE:更新:
If let ambassador = {};
如果let ambassador = {};
then abmassador
is truthy
so you can check keys of the object:那么abmassador
是truthy
所以你可以检查对象的键:
let ambassador = {};
console.log(ambassador == null); //false
console.log(typeof(ambassador)); // Object
if (ambassador)
console.log(`ambassador`, Object.keys(ambassador).length > 0 );
In JavaScript, a truthy value is a value that is considered true when encountered in a Boolean context.在 JavaScript 中,真值是在布尔上下文中遇到时被认为是真的值。 All values are truthy unless they are defined as falsy (ie, except for false, 0, 0n, "", null, undefined, and NaN).所有值都是真值,除非它们被定义为假(即,假、0、0n、""、null、未定义和 NaN 除外)。
Examples of truthy values in JavaScript (which will be coerced to true in boolean contexts, and thus execute the if block): JavaScript 中的真值示例(在布尔上下文中将被强制为真,从而执行 if 块):
if (true)
if ({})
if ([])
if (42)
if ("0")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.