Reputation: 1220
Given the following
var content = [{
"set_archived": false,
"something": [{
"id": "aa7bb3db-19a2-4ef6-5944-892edaaf53c3",
"modified": "2016-12-01T18:23:29.743333Z",
"created": "2016-12-01T18:23:29.743333Z",
"archived": false
}]
},
{
"set_archived": true,
"something": [{
"id": "aa7bb3db-19a2-4ef6-5944-892edaaf53c3",
"modified": "2017-01-30T19:42:29.743333Z",
"created": "2017-01-30T19:42:29.743333Z",
"archived": false
}]
}
];
Using Lodash, how would I determine if either set_archived
or something.archived
in the array of objects is equal to true?
So in this case, because the second object has set_is_archived
that is true, then the expected response should be true. If all items are false in either object, then the response should be false.
Upvotes: 2
Views: 12992
Reputation: 3627
Considering the same object as the one in the question, there are couple of ways to find the solution to your problem mate.
var flag = false;
flag = content.some(function(c){
if(c["set_archived"]){
return true;
}
});
console.log(flag)
or
var flag = false;
flag = content.some(function(c){
if(c["set_archived"] || c.something[0].archived){
return true;
}
});
console.log(flag)
The above snippet will result true if atleast one of the object of the array have ["set_archived"] property true and it will return false if all the objects of the array has ["set_archived"] as false. (I could have said vice-versa)
The some() method tests whether some element in the array passes the test implemented by the provided function.
The every() method tests whether all elements in the array pass the test implemented by the provided function.
If you are looking for a stricter way I recon you go ahead with every().
Upvotes: 1
Reputation: 36189
You don't need lodash for this. You can do this with pure JS, using filter
:
content.filter(i => i.set_archived || i.something.archied)
Upvotes: 0
Reputation: 122027
You can just use some()
in plain javascript.
var content = [{
"set_archived": false,
"something": [{
"id": "aa7bb3db-19a2-4ef6-5944-892edaaf53c3",
"modified": "2016-12-01T18:23:29.743333Z",
"created": "2016-12-01T18:23:29.743333Z",
"archived": false
}]
}, {
"set_archived": true,
"something": [{
"id": "aa7bb3db-19a2-4ef6-5944-892edaaf53c3",
"modified": "2017-01-30T19:42:29.743333Z",
"created": "2017-01-30T19:42:29.743333Z",
"archived": false
}]
}];
var result = content.some(function(e) {
return e.set_archived === true || e.something[0].archived === true
})
console.log(result)
Upvotes: 1
Reputation: 14257
Just use:
_.filter(content, o => o["set_archived"] || o.something[0].archived).length > 0;
or
_.some(content, o => o["set_archived"] || o.something[0].archived);
PlainJs:
content.some(o => o["set_archived"] || o.something[0].archived)
or
content.filter(o => o["set_archived"] || o.something[0].archived).length > 0;
Upvotes: 6