Push element item into object list

There is a specific format output that i need from a for loop which are elements inside an object, and also inside array. The output should be as follows:

[
  {
   day1: 0,
   day2: 0,
   day3: 0
  }
]

I understand .push is probably the key here but Im not sure which syntax to follow.

The simplest way to explain what im trying to do is as follows:

 var element = [];

  for (let i = 1; i <= 3; i++) {
    element.push({"day"i: 0});

  }

console.log(element);

>Solution :

Here is how to do it, if I understood the post correctly. Also don’t use var keyword, instead use const for array declarations most of the time. var has some weird behaviour, and it is better to be avoided! 🙂

const element = [];

let obj = {};
for (let i = 1; i <= 3; i++) {
  obj["day" + i] = 0;
}

element.push(obj);

console.log(element);

Leave a Reply