Search code examples
javascriptfor-loopjavascript-objects

Adding elements to an object in a loop


I am trying to add elements to an object in a loop, but the output is unexpected.

I have tried 2 different ways that I have found on SO but neither have worked to the output I need.

request(options, (err, response, body) => {
  if (err) {
    reject(err);
  }
  var data = {};
  var res = JSON.parse(body);

  for (i = 0; i < res.teams.length; i++) {
    data[i] = { name: res.teams[i].name, id: res.teams[i].id };
  }
  console.log(data.name);

The problem with this is it outputs: '0': { name: 'test', id: 1 }. The '0' at the beginning is problematic. The other way I have tried is simply:

request(options, (err, response, body) => {
  if (err) {
    reject(err);
  }
  var data = {};
  var res = JSON.parse(body);

  for (i = 0; i < res.teams.length; i++) {
    data += { name: res.teams[i].name, id: res.teams[i].id };
  }
  console.log(data.name);

The problem with this is it displays [object, Object] 20 times.

I am trying to just get an output of my object like:

{ { name: 'test1', id: 1 },
  { name: 'test2', id: 2 },
}

Solution

  • What I would suggest is an array filled with objects. What you are trying to do right now is not valid. Here's an example of the proper formatting:

    [ { name: 'test1', id: 1 },
      { name: 'test2', id: 2 },
    ]
    

    This is how I would refactor your code:

    var data = [];
    var res = JSON.parse(body);
    
    for (i = 0; i < res.teams.length; i++) {
        data.push({ name: res.teams[i].name, id: res.teams[i].id });
    }
    console.log(data);
    

    This way you will have to loop over the array to access each object, such as getting { name: 'test1', id: 1 } by accessing data[0].