Reputation: 12923
At the core of the problem I have:
[
{amount: 0, name: "", icon: "", description: ""} // default object added to array
{amount: 1, name: "kjfhdkfjh", icon: "67", description: "dasdasd"}
]
I want to know how to use lodash find such that, as long as any key has a value other then 0
or ""
we are not considered "empty".
So in this case lodash find would return:
[
{amount: 1, name: "kjfhdkfjh", icon: "67", description: "dasdasd"}
]
Or it would return undefined.
What I have is:
lodashFind(theArray, function(obj){
// Now what? How do I go through the objects?
});
I am not sure how to go through objects saying, as long as there is no 0
for amount and no string has ""
then return that object.
Ideas?
Upvotes: 1
Views: 1360
Reputation: 29906
Use _.filter
, _.some
, _.all
or _.negate
of lodash to achieve this:
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
and _.all
search for truthy values, ''
and 0
is not truthy. Namely, the following JavaScript values are falsy: false, 0, '', null, undefined, NaN
. Every other value is truthy.
Upvotes: 4
Reputation: 318182
Using just regular javascript, this is quite easy as well, just filter the array based on the objects values etc, like this
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;
});
Upvotes: 0