Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript lodash:从对象数组中获取对象-深度搜索和多个谓词_Javascript_Arrays_Lodash - Fatal编程技术网

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);