2

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 },
}
2
  • 2
    What you're trying to get is not a valid JS object Commented Aug 27, 2019 at 18:11
  • Sounds like you want an array of objects. In which case start with an empty array and push each object onto it Commented Aug 27, 2019 at 18:15

2 Answers 2

1

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].

Sign up to request clarification or add additional context in comments.

Comments

0

That would solve your problem, try this on js fiddle:

  //Assuming the response body:
  // {
  //		teams: [{id: 1, name: 'one'}, {id: 2, name: 'two'}],
  //    otherField: 'something here'
	// }
  var data = {};
  // Assuming response string is already parsed
  var res = {
  	teams: [{id: 1, name: 'one'}, {id: 2, name: 'two'}],
    otherField: 'something here'
  };

	res.teams.forEach((element, index, originalArray) => {
  	data = {
    // destructuring assignment. See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
			...data,
      // Define field using braces
      ['team'+index]: element
    };
  });
  
  // Now lets show all of them. Using map() just to show you a new method
  Object.keys(data).map((element, index) => {
  	console.log(data[element].name);
  });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.