Javascript lodash 检查对象属性有值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44962321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
lodash check object properties has values
提问by Celdric Kang
I have object with several properties, says it's something like this
我有几个属性的对象,说它是这样的
{ a: "", b: undefined }
in jsx is there any one line solution I can check whether that object's property is not empty or has value or not? If array there's a isEmpty method.
在 jsx 中是否有任何一行解决方案我可以检查该对象的属性是否不为空或是否有值?如果数组有一个 isEmpty 方法。
I tried this
我试过这个
const somethingKeyIsnotEmpty = Object.keys((props.something, key, val) => {
return val[key] !== '' || val[key] !== undefined
})
回答by Mukesh Soni
In lodash, you can use _.some
在 lodash 中,你可以使用 _.some
_.some(props.something, _.isEmpty)
回答by Marian Gálik
You can use lodash _.everyand check if _.valuesare _.isEmpty
您可以使用 lodash_.every并检查是否_.values是_.isEmpty
const profile = {
name: 'John',
age: ''
};
const emptyProfile = _.values(profile).every(_.isEmpty);
console.log(emptyProfile); // returns false
回答by Mayank Shukla
Possible ways:
可能的方法:
Iterate all the keys and check the value:
迭代所有键并检查值:
let obj = {a:0, b:2, c: undefined};
let isEmpty = false;
Object.keys(obj).forEach(key => {
if(obj[key] == undefined)
isEmpty = true;
})
console.log('isEmpty: ', isEmpty);
Use Array.prototype.some(), like this:
使用Array.prototype.some(),像这样:
let obj = {a:0, b:1, c: undefined};
let isEmpty = Object.values(obj).some(el => el == undefined);
console.log('isEmpty: ', isEmpty);
Check the index of undefinedand null:
检查的指标undefined和null:
let obj = {a:1, b:2, c: undefined};
let isEmpty = Object.values(obj).indexOf(undefined) >= 0;
console.log('isEmpty: ', isEmpty);

