在多个对象数组中添加键值

时间:2018-02-27 10:08:12

标签: javascript angular

Array [ Object, Object, Object, Object ]

Object {
  id : 1,
  name : xyz,
  section : b
},{
  id : 2,
  name : abc,
  section : a
},

$scope.array = Array [ Object, Object, Object, Object ];

          angular.forEach$scope.array, function(value, key){
              $scope.array.push({
                'new_va' : 1
              })
          }

如何为每个对象添加新的键值,请指导 我尝试了不同的方式,但不起作用,提前谢谢你

3 个答案:

答案 0 :(得分:1)

这是我的解决方案:

$scope.array.forEach(function(obj, key){
    obj['new_va'] = 1;
})

答案 1 :(得分:0)

使用mapObject.assign

var output = arr.map( s => Object.assign( s, s, { 'new_va' : 1 } ) )

<强>演示

var arr = [{
  id : 1,
  name : "xyz",
  section : "b"
},{
  id : 2,
  name : "abc",
  section : "a"
}]
var output = arr.map( s => Object.assign( s, s, { 'new_va' : 1 } ) );

console.log(output);

答案 2 :(得分:0)

试试这个

&#13;
&#13;
var arr = [{
    id: 1,
    name: 'xyz',
    section: 'b'
}, {
    id: 2,
    name: 'abc',
    section: 'a'
}];

arr.forEach(ele => ele.new_va = 1);
console.log(arr);
&#13;
&#13;
&#13;