[英]Check array of objects in lodash for property value
鑒於以下
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
}]
}
];
使用Lodash,我如何確定對象數組中的set_archived
或something.archived
等於true?
因此,在這種情況下,由於第二個對象的set_is_archived
為true,因此預期響應應該為true。 如果在任何一個對象中所有項目均為假,則響應應為假。
只需使用:
_.filter(content, o => o["set_archived"] || o.something[0].archived).length > 0;
要么
_.some(content, o => o["set_archived"] || o.something[0].archived);
PlainJs:
content.some(o => o["set_archived"] || o.something[0].archived)
要么
content.filter(o => o["set_archived"] || o.something[0].archived).length > 0;
您可以在純JavaScript中使用some()
。
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)
您不需要lodash。 您可以使用filter
使用純JS來做到這一點:
content.filter(i => i.set_archived || i.something.archied)
考慮到與問題中的對象相同的對象,有兩種方法可以找到問題伴侶的解決方案。
var flag = false;
flag = content.some(function(c){
if(c["set_archived"]){
return true;
}
});
console.log(flag)
要么
var flag = false;
flag = content.some(function(c){
if(c["set_archived"] || c.something[0].archived){
return true;
}
});
console.log(flag)
如果該數組的至少一個對象具有[“ set_archived”]屬性為true,則上述代碼片段將為true;如果該數組的所有對象都具有[“ set_archived”]為false,則上述代碼段將返回false。 (反之亦然)
some()方法測試數組中的某些元素是否通過提供的函數實現的測試。
every()方法測試數組中的所有元素是否通過提供的函數實現的測試。
如果您正在尋找更嚴格的方法,我建議您繼續使用every()。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.