简体   繁体   English

lodash:从对象数组中获取对象-深度搜索和多个谓词

[英]lodash: get object from an array of objects - deep search and multiple predicates

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 我想得到一个new: true对象new: trueamount最大

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. 您仍然需要处理在new为true且有多个最大金额时发生的情况。

With lodash 4.x: 使用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();

jsfiddle 的jsfiddle

Plain JavaScript 纯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's answer works but I prefer functional style over chaining style . 亚历山大的答案很有效,但我更喜欢功能样式而不是链接样式

With Lodash 洛达什

result = _.maxBy(_.filter(_.flatten(_.values(objs)), 'new'), 'amount');

DEMO DEMO

With Lodash/fp 使用Lodash / fp

result = _.compose(_.maxBy('amount'), _.filter('new'), _.flatten, _.values)(objs);

DEMO DEMO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM