Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lodash forEach function omit

I have an object in my .js file (node)

var z = [
    {'a': 'uno', 'b': 'dos'},
    {'a': 'uno', 'b': 'dos'},
    {'a': 'uno', 'b': 'dos'},
    {'a': 'uno', 'b': 'dos'}
];

I would like to omit each 'a' from z object.

I'm trying with something like this, but is not working.

var y = _.forEach(z, function(n){
    //console.log(_.omit(n, 'a'));
    return _.omit(n, 'a');
});

console.log(y);

I tried without return, and few ways more, but didn't get it.

My jsfiddle link: http://jsfiddle.net/baumannzone/jzs6n78m/

Any help? Cheers!

like image 904
Baumannzone Avatar asked Oct 26 '15 15:10

Baumannzone


2 Answers

Create a new array of objects, by omitting a from each of them

console.log(_.map(z, function (obj) {
  return _.omit(obj, 'a');
}));
// [ { b: 'dos' }, { b: 'dos' }, { b: 'dos' }, { b: 'dos' } ]

As it is, you are omitting and creating a new object but that object is ignored by _.each. Now, we use _.map, which will gather all the values returned from the function and form a new array.


If you prefer a one-liner, create a partial function and leave only the object to be used as _, like this

console.log(_.map(z, _.partial(_.omit, _, 'a')));
// [ { b: 'dos' }, { b: 'dos' }, { b: 'dos' }, { b: 'dos' } ]
like image 52
thefourtheye Avatar answered Sep 30 '22 06:09

thefourtheye


var y = _.map(z, function(n) {
    return _.omit(n, 'a');
});

This will create a new array from the old one, mapping the objects in z to new objects that omit the 'a' attribute.

An alternative is to use chaining, so:

var y = _(z).map(function(n){return n.omit('a');}).value();

B

like image 40
Software Engineer Avatar answered Sep 30 '22 06:09

Software Engineer