简体   繁体   中英

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

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.

With 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

Plain 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

With Lodash/fp

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

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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