-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
  • 1
    It's not really an object. It's an array of 1 object. (And it's definitely not JSON. The keys would need to be in double quotes like "Yogi") Commented Jan 26, 2018 at 15:05
  • Adult polar bears are much heavier than that, but I won't downvote for a data error:) Commented Jan 26, 2018 at 15:50

2 Answers 2

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>);
Sign up to request clarification or add additional context in comments.

3 Comments

yes, it's an array containing object, just like in the description.
and nope, this doesn't work, I don't get strings, I got all objects with this solution.
@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.
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>
    );
  }

2 Comments

make sure to try my code I haven't compiled it.
cannot change JSON structure. Thats the whole point my friend...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.