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