1

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?

1
  • It is not clear what you wish to achieve, you should provide an example output. You said that an object is not empty if it has at least one non-empty field, but after you say that you search for objects not containing 0 or "". It is a contradiction Commented Dec 5, 2015 at 18:40

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

FIDDLE

2 Comments

I asked for lodash because its more readable in 6 months when I come back to the code
@KyleAdams - I just thought I'd post a plain JS answer, as to me this is a lot more readable than the Lodash code above

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.