admin管理员组

文章数量:1292052

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: /

Any help? Cheers!

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/baumannzone/jzs6n78m/

Any help? Cheers!

Share edited Oct 26, 2015 at 15:07 thefourtheye 240k53 gold badges465 silver badges500 bronze badges asked Oct 26, 2015 at 15:02 BaumannzoneBaumannzone 7802 gold badges20 silver badges38 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

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

本文标签: javascriptLodash forEach function omitStack Overflow