Creating new javascript Object form existing one

2019-08-04 10:13发布

问题:

I have my original objects as follow. All I need is to just extract few properties from existing one and create new object.

var data = [{
    id: 3,
    name: Axe,
    location: alkt
}, {
    id: 5,
    name: Roy,
    location: grelad
}]

I need my output as,

var data_new = [{
    id: 3,
    name: Axe
}, {
    id: 5,
    name: Roy,
}]

How to implement in underscore js or any simple method. Possible its a large JSON object.

回答1:

If there are just few properties you want to extract then simple Array.prototype.map will works fine:

var data = [{
    id: 3,
    name: 'Axe',
    location: 'alkt'
}, {
    id: 5,
    name: 'Roy',
    location: 'grelad'
}]

var result = data.map(function(obj) {
    return {
      id: obj.id,
      name: obj.name
    };
});

alert(JSON.stringify(result, null, 4));



回答2:

Use pick in undescorejs http://underscorejs.org/#pick Or omit http://underscorejs.org/#omit

_.pick({name: 'moe', age: 50, userid: 'moe1'}, 'name', 'age');
=> {name: 'moe', age: 50}
_.pick({name: 'moe', age: 50, userid: 'moe1'}, function(value, key, object) {
  return _.isNumber(value);
});
=> {age: 50}


回答3:

It you want remove each item's location

var data_new = _.map(data, function(item) {
  return _.omit(item, 'location');
});


回答4:

If all you want is remove properties from objects in an array, you could just delete them while iterating with forEach:

var data_new = data;
data_new.forEach(function(obj){ delete obj.location; /* or any other */ });


回答5:

$scope.data_new = [];
for(i in $scope.data){
  $scope.data_new.push(
   { id: $scope.data[i].id, name: $scope.data[i].name }
  )
}