Bird
Bird

Reputation: 81

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'
  }];

Upvotes: 2

Views: 12237

Answers (3)

Atul Arvind
Atul Arvind

Reputation: 16743

The one-line solution can be

_.map(array, o => _.omit(o, ['id', 'name']));

or

_.map(array, o => _.pick(o, ['age', 'city']));

Upvotes: 0

LordKayBanks
LordKayBanks

Reputation: 71

const 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' }];

const result = array.map(({age, city})=>( {age, city}));

Upvotes: 0

Ori Drori
Ori Drori

Reputation: 191986

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>

Upvotes: 7

Related Questions