I have this:
objs = {
obj1 : [{ amount: 5, new: true }, { amount: 3, new: false }],
obj2: [{ amount: 1, new: true }, { amount: 2, new: false }]
}
And I want get one object where new: true
and with maximum value of 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);
You still need to handle what happens when new is true and there are multiple max amounts.
With 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();
Plain 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));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.