搜索寻找非空对象JS的对象数组

时间:2015-12-05 18:24:25

标签: javascript lodash

问题的核心是:

[
  {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且没有字符串""然后返回该对象。

思想吗

2 个答案:

答案 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;
});

FIDDLE