js 物件陣列新增屬性、修改屬性
阿新 • • 發佈:2019-01-05
var kvArray = [{key: 1, value: 10}, {key: 2, value: 20}, {key: 3, value: 30}]; var reformattedArray = kvArray.map(function(obj,index) { console.log(index) var rObj = {}; rObj.id=index;//新增id屬性 rObj[obj.key] = obj.value;//修改屬性 return rObj; }); console.log(reformattedArray); var reformattedArray2 = kvArray.map(function(obj,index) { obj.id=index;//新增id屬性 return obj;//如果不返回則輸出: Array [undefined, undefined, undefined] }); console.log(reformattedArray2);
輸出:
> 0
> 1
> 2
> Array [Object { 1: 10, id: 0 }, Object { 2: 20, id: 1 }, Object { 3: 30, id: 2 }]
> Array [Object { key: 1, value: 10, id: 0 }, Object { key: 2, value: 20, id: 1 }, Object { key: 3, value: 30, id: 2 }]
參考:
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/map