Search code examples
objectlodasharrayobject

Lodash _.omit function inside map


I'm trying to write a function, that will transform an array of objects.

var array = [{
    id: 1,
    name: 'Peter',
    age: 29,
    city: 'New York'
}, {
    id: 2,
    name: 'Peter2',
    age: 19,
    city: 'LA'
}, {
    id: 3,
    name: 'Peter3',
    age: 89,
    city: 'Rio'
}];

function mapArray(array) {
    _.map(array, object => {
        _.omit(object, ['id', 'name']);
    });

    return array;
}

And it doesn't work. As a result I get an array with all the fields. Lodash version is 4.17.4. I also use nodejs, if it matters :D

As the result I want to get array of objects like this:

[{
    age: 29,
    city: 'New York'
  }, {
    age: 19,
    city: 'LA'
  }, {
    age: 89,
    city: 'Rio'
  }];

Solution

  • Both _.map() and _.omit() return a new array/object respectively, and don't change the original item. You have to return the results of the map, and remove the curly brackets wrapping the omit (which is inside an arrow function):

    var array = [{"id":1,"name":"Peter","age":29,"city":"New York"},{"id":2,"name":"Peter2","age":19,"city":"LA"},{"id":3,"name":"Peter3","age":89,"city":"Rio"}];
    
    function mapArray(array) {
      // return from _.map
      return _.map(array, object =>
        _.omit(object, ['id', 'name']) // return from _.omit
      );
    }
    
    // assign the results to a new variable
    var result = mapArray(array);
    
    console.log(result);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>