如何在javascript中向现有对象添加新对象属性?

时间:2017-05-06 15:54:28

标签: javascript arrays

我有一系列对象,让我们说array[object,object....]。我想为数组中的每个对象添加一个新属性。 下面我提到了现有的阵列和我想要的结果。

现有数组:

array[ {"name":"Siddhesh mishra","add":"hjhjjdjkhjibf",}
       {"name":"Brijesh mishra","add":"jkfhgfbrfhiurf"} ]

我想要这个数组:

array[ {"name":"Siddhesh mishra","add":"hjhjjdjkhjibf","mobile":"95937338373"}
       {"name":"Brijesh mishra","add":"jkfhgfbrfhiurf","mobile":"78984983498"} ]

我该怎么做?

2 个答案:

答案 0 :(得分:1)

你可以这样做。让一个移动号码数组的长度与array的长度相同。循环遍历array数组并添加mobile键和来自mobNum数组的值



var mobNum=[1,2];
var array = [{
  "name": "Siddhesh mishra",
  "add": "hjhjjdjkhjibf"
}, {
  "name": "Brijesh mishra",
  "add": "jkfhgfbrfhiurf"
}]
array.forEach(function(item,index){
  item.mobile=mobNum[index]
})
console.log(array)




答案 1 :(得分:0)

var data = [ {"name":"Siddhesh mishra","add":"hjhjjdjkhjibf"},
       {"name":"Brijesh mishra","add":"jkfhgfbrfhiurf"} ];


data.map(function(entry){
  //add logic to get mobile number from entry.name or entry.add
  return entry.mobile = '98989898';
})

console.log(data);