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?

1
  • JSON is a textual notation for data exchange. (More) 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. Commented Oct 2, 2016 at 7:26

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.