-3

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 "age":"18" to all the records:

[{"name":"albin", "age":"18"},{"name", "alvin", "age":"18"}];
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
Alvin
  • 8,219
  • 25
  • 96
  • 177

2 Answers2

4

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
});

console.log(data);

Note: The json in the question is not valid

JSFIDDLE

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
brk
  • 48,835
  • 10
  • 56
  • 78
0

var data = [{"name": "albin"}, {"name": "alvin"}];
for (var i = 0; i < data.length; i++) {
    data[i].age = "18";
}
Cerbrus
  • 70,800
  • 18
  • 132
  • 147