Reputation: 25
There are many objects in the JSON file that look like I have shown below. I want to give an index number starting from 0
for each of these objects. How can I do it?
[
{
"language": "Python",
"created": "2018-8-27 14:50:31",
"evaluated": true,
"hiddenCode": false
},
...
]
Upvotes: 0
Views: 3884
Reputation: 3189
You can use Array.prototype.map()
(MDN) to get new, indexed, array.
var array = [{
"language": "Python1",
"created": "2018-8-27 14:50:31",
"evaluated": true,
"hiddenCode": false
}, {
"language": "Python2",
"created": "2018-8-27 14:50:31",
"evaluated": true,
"hiddenCode": false
}]
const indexed = array.map((item, index) => Object.assign(item, { index }))
console.log(indexed)
Upvotes: 2
Reputation: 1102
Probably something like this if you use ES,
You should use map to iterate over your objects and add the property in it
var yourObjects =[ {
"language": "Python1",
"created": "2018-8-27 14:50:31",
"evaluated": true,
"hiddenCode": false
}, {
"language": "Python2",
"created": "2018-8-27 14:50:31",
"evaluated": true,
"hiddenCode": false
}
];
var i = 0;
yourObjects.map(
(obj) => {
obj['index'] = i;
i++
return obj;
});
console.log(yourObjects);
Upvotes: 0
Reputation: 765
You can loop on the objects and add new property,
var array =[ {
"language": "Python1",
"created": "2018-8-27 14:50:31",
"evaluated": true,
"hiddenCode": false
}, {
"language": "Python2",
"created": "2018-8-27 14:50:31",
"evaluated": true,
"hiddenCode": false
}
];
for (i = 0; i < array.length; i++) {
array[i]["index "] =i;
}
console.log(array);
Upvotes: 1