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

时间:2016-04-17 11:59:26

标签: 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 }

4 个答案:

答案 0 :(得分:0)

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

你还需要处理当new为真时会发生什么   多个最大金额。

答案 1 :(得分:0)

使用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

答案 2 :(得分:0)

普通JavaScript

&#13;
&#13;
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));
&#13;
&#13;
&#13;

答案 3 :(得分:0)

亚历山大的答案有效,但我更喜欢 功能风格 而不是链接风格

使用 Lodash

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

DEMO

Lodash / fp

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

DEMO