Creating new javascript Object form existing one

馋奶兔 提交于 2019-12-13 00:24:49

问题


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 }
  )
}


来源:https://stackoverflow.com/questions/31263886/creating-new-javascript-object-form-existing-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!