Alvin Alvin - 1 year ago 63
Javascript Question

How to add an element to all objects in an array

I have an array of objects:

var data = [{"name":"albin"},{"name", "alvin"}];

How can I add an element to all the records?

I want to add
to all the records:

[{"name":"albin", "age":"18"},{"name", "alvin", "age":"18"}];

Answer Source

Use forEach to iterate through the through this json array & add a key age to each of the object

var data = [{
  "name": "albin"
}, {
  "name": "alvin"

data.forEach(function(item) {
  item.age = 18


Note: The json in the question is not valid


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download