Lodash - Conditionally returned object from a map method

I want to iterate over an array, do a calculation, and if the condition is true for the result, return a new object. _.filter(...)does not work here, since the iterator function should return either true, or false.

_.map(people, function(person) {

    var age = calculateAge(person.birthDate);

    if (age > 50) {
        return {person: person, age: age};
    }

});

I tried searching everything, including the documentation, but I did not find a way to do this well.

+4
source share
3 answers

It looks like you want reduce, 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;
}, []);

<y> Also, if you use ES6 + and / or use Babel, this can be useful for understanding lists:

let newArray = [for (person of people)
                if (calculateAge(person.birthDate) > 50)
                { person: person, age: calculateAge(person.birthDate) }
               ];

Refresh . The list of passports was excluded from Babel 6. ES2015 version will look like this:

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)

+10

:

var sorted = _.filter(people, function(person) {

    var age = calculateAge(person.birthDate);

    if (age > 50) {
      return true;
    }
});

var newArray = _.map(sorted, function(person) {

   var age = calculateAge(person.birthDate);

   return {person: person, age: age};
});

, , 50.

0

Try the following:

people = _.pluck(
                _.filter(
                        _.map(people, function(person) {
                            return { person: person, age: calculateAge(person.birthDate) };
                        }), 
                        function(person) {
                            return person.age > 50;
                        }
                ), 
                "person"
        );

See fiddle section

0
source

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


All Articles