Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a column to items in an array?

I have a Json object coming from a backend server called Data like this:

[{
  "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"
}]

and I would like to add a column (property?) to each row like this:

[{
  "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": ""
}]

Does anyone how I can do this?

Thanks in advance.

like image 796
Philippe Corrèges Avatar asked Dec 08 '22 20:12

Philippe Corrèges


1 Answers

Try this:

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

Needs that typeof check because of that weird 3 in the middle.

like image 196
nvioli Avatar answered Dec 11 '22 09:12

nvioli