提问人:Laura Drill 提问时间:8/15/2023 更新时间:8/15/2023 访问量:45
是否有 Javascript/Lodash 函数来检查对象是否缺少任何属性?
Is there a Javascript/Lodash function to check if an object is missing ANY properties?
问:
我想检查一个 javascript 对象,看看它是否缺少任何属性,而无需单独检查每个属性。
我可以使用“hasownproperty”或执行 if/else 语句来检查每个语句是否为 null/undefined,我想要一种更短的检查对象的方法。
答:
0赞
mplungjan
8/15/2023
#1
也许是这个?
const hasMissing = obj => {
const vals = Object.values(obj);
return vals.filter(val => val !== null && val !== undefined).length !== vals.length
};
const obj = { "a":null, "b":"there", "c":0, "d":undefined }
console.log(obj);
console.log(JSON.stringify(obj)); // so we cannot use that
console.log("Missing?",hasMissing(obj))
0赞
Alexander Nenashev
8/15/2023
#2
对对象值使用(使用 ) 获取它们(如果 ANY 属性的值为 或,这将返回):Array::some()
Object.values()
true
null
undefined
const obj = { a: null, b: 'there', c: 0, d: undefined };
console.log("Missing?", Object.values(obj).some(v => v === undefined || v === null));
如果您想要尽可能快的速度,请编写自己的函数:
const obj = { a: null, b: 'there', c: 0, d: undefined };
function hasNullProperties(obj){
for(const k in obj){
if(obj[k] === undefined || obj[k] === null){
return true;
}
}
return false;
}
console.log("Missing?", hasNullProperties(obj));
还有一个基准:
<script benchmark data-count="10000000">
const obj = { a: null, b: 'there', c: 0, d: undefined };
// @benchmark Array::some()
Object.values(obj).some(v => v === undefined || v === null);
// @benchmark custom func
function hasNullProperties(obj){
for(const k in obj){
if(obj[k] === undefined || obj[k] === null){
return true;
}
}
return false;
}
// @run
hasNullProperties(obj);
</script>
<script src="https://cdn.jsdelivr.net/gh/silentmantra/benchmark/loader.js"></script>
评论
{ foo: 1, bar: null }
bar
{ foo: 2 }
bar