Lodash: get an object from an array of objects - deep search and multiple predicates

I have it:

objs = { obj1 : [{ amount: 5, new: true }, { amount: 3, new: false }], obj2: [{ amount: 1, new: true }, { amount: 2, new: false }] } 

And I want to get one object where new: true and with a maximum value of amount

 result = { amount: 5, new: true } 
+2
source share
4 answers

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

0
source
 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 the new is true, and there are a few maximum amounts.

0
source

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

Alexander's answer works, but I prefer a functional style to a chain 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

0
source

Source: https://habr.com/ru/post/1247289/


All Articles