I want to iterate through an array, run a calculation, and if the condition is true for the result, return a new object. _.filter(...)
would not work here, since the iterator function must return either true
or false
.
_.map(people, function(person) {
var age = calculateAge(person.birthDate);
if (age > 50) {
return {person: person, age: age};
}
});
I've tried searching all over, including the documentation, but I haven't found a way to do this well.
Sounds like maybe you want reduce
and not map
:
var newArray = _.reduce(people, function(results, person) {
var age = calculateAge(person.birthDate);
if (age > 50) {
results.push({ person: person, age: age });
}
return results;
}, []);
Also if you are ES6+ and/or using Babel, this might be a good use for list comprehensions:
let newArray = [for (person of people)
if (calculateAge(person.birthDate) > 50)
{ person: person, age: calculateAge(person.birthDate) }
];
Update: List comprehensions have been dropped from from Babel 6. The ES2015 version would look like:
const newArray = people.reduce((results, person) => {
const age = calculateAge(person.birthDate);
return (age > 50) ? [...results, { person, age }] : results;
}, []);
(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With