如何向数组中的项添加列?

时间:2016-12-28 14:20:09

标签: javascript typescript

我有一个Json对象来自一个名为Data的后端服务器,如下所示:

[{
  "categoryName": "Google",
  "id": "58591d2b7672d99910497bec",
  "clientId": "585808f6737f6aad1985eab2"
}, {
  "categoryName": "Microsoft",
  "id": "58591d3d7672d99910497bee",
  "clientId": "585808f6737f6aad1985eab2"
}, "3", {
  "categoryName": "Yahoo",
  "id": "58591d4c7672d99910497bef",
  "clientId": "585808f6737f6aad1985eab2"
}, {
  "categoryName": "Msn",
  "id": "585d25f6ae4b2ecb056bc514",
  "clientId": "585808f6737f6aad1985eab2"
}]

我想在每一行添加一列(属性?),如下所示:

[{
  "categoryName": "Google",
  "id": "58591d2b7672d99910497bec",
  "clientId": "585808f6737f6aad1985eab2",
  "new column": ""
}, {
  "categoryName": "Microsoft",
  "id": "58591d3d7672d99910497bee",
  "clientId": "585808f6737f6aad1985eab2",
  "new column": ""
}, "3", {
  "categoryName": "Yahoo",
  "id": "58591d4c7672d99910497bef",
  "clientId": "585808f6737f6aad1985eab2",
  "new column": ""
}, {
  "categoryName": "Msn",
  "id": "585d25f6ae4b2ecb056bc514",
  "clientId": "585808f6737f6aad1985eab2",
  "new column": ""
}]

有人怎么能这样做?

提前致谢。

2 个答案:

答案 0 :(得分:5)

你可以这样做:

const arr = data.map(x => Object.assign({}, data, { "new column": "" }))

答案 1 :(得分:4)

试试这个:

data.forEach(function(e){
  if (typeof e === "object" ){
    e["new column"] = ""
  }
});

由于中间那个奇怪的3,需要进行类型检查。