Add property/index to each element in an array

There is nothing really special to do. Simply iterate over the array and add the property to each element:

for (var i = 0; i < foo.length; i++) {
  foo[i].row_number = i;
}

// or with forEach

foo.forEach(function(row, index) {
  row.row_number = index;
});

See Access / process (nested) objects, arrays or JSON for more general information about nested data structures in JavaScript.


You could also use map in case you want to keep the old object around, or wanted to do it in a call chain not modifying an existing array.

const oldArray = [{a: 'Andy'}, {b: 'Betty'}, {c: 'Charlie'}];
const newArray = oldArray.map((item, index) => ({index, ...item}));
console.log(newArray);
// Array [Object { index: 0, a: "Andy" }, Object { index: 1, b: "Betty" }, Object { index: 2, c: "Charlie" }]

Tags:

Javascript