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
且最大值为 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.
使用 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));
Alexander 的回答有效,但我更喜欢 函数式风格 而不是 链接风格 .
与Lodash
result = _.maxBy(_.filter(_.flatten(_.values(objs)), 'new'), 'amount');
和Lodash/fp
result = _.compose(_.maxBy('amount'), _.filter('new'), _.flatten, _.values)(objs);
我有这个:
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 }
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.
使用 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));
Alexander 的回答有效,但我更喜欢 函数式风格 而不是 链接风格 .
与Lodash
result = _.maxBy(_.filter(_.flatten(_.values(objs)), 'new'), 'amount');
和Lodash/fp
result = _.compose(_.maxBy('amount'), _.filter('new'), _.flatten, _.values)(objs);