skip to Main Content

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


  1. As @mamun mentioned, you are reassigning obj['arr'] in each iteration.

    Instead, do this:

    const obj = {};
    obj['arr'] = [];
    
    for (let i = 0; i < 5; i++) {
      obj["arr"].push(i);
    }
    
    console.log(obj["arr"]);
    
    Login or Signup to reply.
  2. 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 exists

    const obj = {};
    
    for (let i = 0; i < 5; i++) {
      obj['arr'] ??= [];
      obj['arr'].push(i);
    }
    
    console.log(obj['arr']);

    It is of course only interesting in more complex object loops but very useful.

    If you have a simple loop then

    const obj = { "arr":[] };
    
    for (let i = 0; i < 5; i++) {
      obj['arr'].push(i);
    }
    
    console.log(obj['arr']);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search