我有一个对象,有时候它是空的,就像{}
一样,有时候它的属性会被设置为null。
{
property1: null,
property2: null
}
如何确定此对象中的所有属性是否都为空?如果它们都为空,则返回false。
目前,我正在使用lodash检查第一种情况,即对象只是{}
为空。但我还需要介绍第二种情况。
if (isEmpty(this.report.device)) {
return false;
}
return true;
发布于 2018-05-31 16:32:25
您可以使用Object.values
将对象转换为数组,并使用every
检查每个元素。使用!
对该值求反。
let report = {
property1: null,
property2: null,
}
let result = !Object.values(report).every(o => o === null);
console.log(result);
例如,某些元素不是null
let report = {
property1: null,
property2: 1,
}
let result = !Object.values(report).every(o => o === null);
console.log(result);
发布于 2018-05-31 16:32:18
您可以使用Object.keys()
方法,这将以数组的形式返回该对象中的所有键。这使得执行Object.keys(this.report.device).filter(key => !this.report.device[key] === null)
成为可能,它将返回非空键的数量,如果这是0,那么您就得到了答案。
本质上,依赖于null
属性并不是一种好的方法,最好将这些属性设为undefined
,或者仅仅从你的API中返回一个平面对象。
希望这能帮上忙。
https://stackoverflow.com/questions/50619910
复制相似问题