Skip to content Skip to sidebar Skip to footer

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 whe

Solution 1:

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

Solution 2:

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.

Solution 3:

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

Solution 4:

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

Post a Comment for "Lodash: Get Object From An Array Of Objects - Deep Search And Multiple Predicates"