When considering your approach, it's important to think about whether you want to alter the input or not.
For example, using a forEach
method may change the original input, which is not always advised.
Take a look at this:
var data = [{Name:'ABC',Code: 'BP'}]
const mutate = data.map((x, i) => (x.ID = i, x))
console.log(data)
This is similar to using forEach
, where you can see that the data was indeed mutated
.
Now, let's explore a more pure function approach:
var data = [{Name:'ABC', Code: 'BP'}]
const pure = data.map((x, i) => ({...x, ID:i}))
console.log(data, pure)
Notice how in the pure approach, the input data remained unchanged and we still achieved the desired output.