-1

I have an object in array like the following:

bears: [
{
 Yogi: "123kg",
 Pooh: "110kg",
 Grizly: "112kg",
 BooBoo: "200kg",
 Polar: "100kg",
}
]

`

What is the best way to iterate through such object in order to display both names and values in the row, like returning something in the type of: <p>${name} ${value}</p>

So I would display:

Yogi 123kg

Pooh 110kg

Grizly 112kg

BooBoo 200kg

Polar 100kh

2 Answers2

4

It's an array containing an object, not an object. Anyway just get the first item of the array.

This should work:

Object.keys(bears[0]).map(key => <p>{`${key} ${bears[0][key]}`}</p>);
Rodius
  • 2,271
  • 14
  • 19
  • yes, it's an array containing object, just like in the description. – Edward Kluczkowski Jan 26 '18 at 15:14
  • and nope, this doesn't work, I don't get strings, I got all objects with this solution. – Edward Kluczkowski Jan 26 '18 at 15:15
  • @EdwardKluczkowski you know you just edited the description and then complained about the description being accurate and we can see your edits, right? It should work now, I copied your OP and you were missing the " ` ". You're welcome. – Rodius Jan 26 '18 at 15:24
0

I think that the JSON object's structure itself is wrong. It should be structured like this:

var bears = [{
  name: "Yogi",
  weight: "123kg"
}, {
  name: "Pooh",
  weight: "110kg"
}, {
  name: "Grizly",
  weight: "112kg"
}, {
  name: "BooBoo",
  weight: "200kg"
}]

Then you can go ahead and iterate through it using a for loop inside of the render() method like this.

render() {
    var bearElements = [];
    for (var bearIndex = 0; bearIndex < bears.length; bearIndex++) {
      bearElements.push(
        <p>{`${bears[bearElements].name}` `${bears[bearElements].weight}`}</p>
      )
    }

    return (
      <div>{bears}</div>
    );
  }
ItzAmmar
  • 53
  • 6