[英]Searching javascript array of objects based on multiple predicates (or) - lodash
[英]lodash: get object from an array of objects - deep search and multiple predicates
我有這個:
objs = {
obj1 : [{ amount: 5, new: true }, { amount: 3, new: false }],
obj2: [{ amount: 1, new: true }, { amount: 2, new: false }]
}
我想得到一個new: true
對象new: true
且amount
最大
result = { amount: 5, new: true }
var result = null;
var maxAmount = -1;
for(key in obj) {
if(obj.hasOwnProperty(key)) {
for(var i = 0, len = obj[key].length; i < len; i++) {
if(obj[key][i].new === true && obj[key][i].amount > maxAmount) {
maxAmount = obj[key][i].amount;
result = obj[key][i];
}
}
}
}
console.log(result);
您仍然需要處理在new為true且有多個最大金額時發生的情況。
使用lodash 4.x:
var objs = {
obj1 : [{ amount: 5, new: true }, { amount: 3, new: false }],
obj2: [{ amount: 10, new: true }, { amount: 2, new: false }]
};
var result = _(objs)
.map(value => value)
.flatten()
.filter(obj => obj.new)
.orderBy('amount', 'desc')
.first();
純JavaScript
var objs = { obj1: [{ amount: 5, new: true }, { amount: 3, new: false }], obj2: [{ amount: 1, new: true }, { amount: 2, new: false }] } var r = objs.obj1.concat(objs.obj2).filter(e => e.new) .sort((a, b) => a.amount - b.amount).pop(); document.write(JSON.stringify(r));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.