Javascript lodash:从对象数组中获取对象-深度搜索和多个谓词
我有这个:Javascript lodash:从对象数组中获取对象-深度搜索和多个谓词,javascript,arrays,lodash,Javascript,Arrays,Lodash,我有这个: 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结果=null; var maxAmount=-1; 用于(输入obj){
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结果=null;
var maxAmount=-1;
用于(输入obj){
if(对象hasOwnProperty(键)){
对于(变量i=0,len=obj[key]。长度;i最大金额){
maxAmount=obj[key][i]。金额;
结果=obj[键][i];
}
}
}
}
控制台日志(结果);
你仍然需要处理当新的是真的并且有
多个最大金额
使用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);
需要检查new===TrueUnrelated,但如果在orderBy之前添加过滤器,则效率会更高。
result = _.compose(_.maxBy('amount'), _.filter('new'), _.flatten, _.values)(objs);