我有这个:
objs = {
obj1 : [{ amount: 5, new: true }, { amount: 3, new: false }],
obj2: [{ amount: 1, new: true }, { amount: 2, new: false }]
}
我想要一个对象new: true
,最大值为amount
result = { amount: 5, new: true }
答案 0 :(得分:0)
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为真时会发生什么 多个最大金额。
答案 1 :(得分:0)
使用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();
答案 2 :(得分:0)
普通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));
&#13;
答案 3 :(得分:0)