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 },
}
pusheach object onto it