I have initialized an empty object in which I am dynamically creating a key and inserting values into it inside for loop.But here issue is its only taking the last value.
Why is it happening so, any correction do I need here.
const obj = {};
for (let i = 0; i < 5; i++) {
obj['arr'] = [];
obj['arr'].push(i);
}
console.log(obj['arr']);
// OUTPUT = [4]
2
Answers
As @mamun mentioned, you are reassigning
obj['arr']
in each iteration.Instead, do this:
As already said, you are creating a new array each time so only the last push is saved.
You can fix this very easily with the nice
??=
Nullish_coalescing_assignment which will assign a new array if one does not already existsIt is of course only interesting in more complex object loops but very useful.
If you have a simple loop then