问题的核心是:
[
{amount: 0, name: "", icon: "", description: ""} // default object added to array
{amount: 1, name: "kjfhdkfjh", icon: "67", description: "dasdasd"}
]
我想知道如何使用lodash查找,只要任何键具有0
或""
之外的其他值,我们就不会被视为“空”。
所以在这种情况下lodash find会返回:
[
{amount: 1, name: "kjfhdkfjh", icon: "67", description: "dasdasd"}
]
或者它会返回undefined。
我拥有的是:
lodashFind(theArray, function(obj){
// Now what? How do I go through the objects?
});
我不知道如何通过对象说,只要数量没有0
且没有字符串""
然后返回该对象。
思想吗
答案 0 :(得分:4)
使用_.filter
的{{1}},_.some
,_.all
或_.negate
来实现此目标:
var data = [
{ name:'a', age:0 },
{ name:'b', age:1 },
{ name:'', age:0 }
];
// lists not empty objects (with at least not empty field)
console.log(_.filter(data, _.some));
// outputs [{name:'a',age:0},{name:'b',age:1}]
// lists 'full' objects (with no empty fields)
console.log(_.filter(data, _.all));
// outputs [{name:'b',age:1}]
// lists 'empty' objects (with only empty fields)
console.log(_.filter(data, _.negate(_.some)));
// outputs [{name:'',age:0}]
_.some
和_.all
搜索 truthy 值,''
和0
并非真实。也就是说,以下JavaScript值是假的:false, 0, '', null, undefined, NaN
。其他所有价值都是真实的。
答案 1 :(得分:0)
使用常规的javascript,这也很容易,只需根据对象值等过滤数组,就像这样
var arr = [
{amount: 0, name: "", icon: "", description: ""},
{amount: 1, name: "kjfhdkfjh", icon: "67", description: "dasdasd"}
]
arr = arr.filter(function(o) {
return Object.keys(o).filter(function(key) {
return o[key] != 0 && o[key].toString().trim().length > 0;
}).length > 0;
});