Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading