ShootingStar ShootingStar - 7 months ago 65
Javascript Question

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 }

Answer

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

Comments