0

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?

javaDeveloper
  • 1,403
  • 3
  • 28
  • 42
  • JSON is a *textual notation* for data exchange. [(More)](http://stackoverflow.com/a/2904181/157247) If you're dealing with JavaScript source code, and not dealing with a *string*, you're not dealing with JSON. I give it about 99% odds you're not dealing with JSON. – T.J. Crowder Oct 02 '16 at 07:26

1 Answers1

2

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.

dfsq
  • 191,768
  • 25
  • 236
  • 258