Rakesh Nair Rakesh Nair - 2 months ago 6
JSON Question

Add a new attribute to json object

I have a

JSON
object of the following format

[{"field1":1,"field2":"A","field3":"B"},
{"field1":2,"field2":"B","field3":"C"},
{......},
{......},
]


I need to add a new attribute to each row based on some calculations.

Expected result

[{"field1":1,"field2":"A","field3":"B","field4"="generatedVal1"},
{"field1":2,"field2":"B","field3":"C","field4"="generatedVal2"},
{......},
{......},
]


How can I achieve this using
javascript
?

Answer

Use Array.prototype.forEach method:

[
  {"field1":1,"field2":"A","field3":"B"},
  {"field1":2,"field2":"B","field3":"C"}
]
.forEach(obj => {
  obj.field4 = 'Something'
})

Sidenote on terminology: you don't have any JSON, you have javascript array (object). JSON is a string representation of this object, but in your question you are talking about object itself.

Comments