Adam
Adam

Reputation: 20872

React Object of Objects - How to loop through

I have the following encoded JSON:

const data = JSON.parse('{"first":{"aaa":"111","bbb":"2222"},"second":{"aaa":"111","bbb":"2222"}}')

After decoding as follows:

{
  "first": {
    "aaa": "111",
    "bbb": "2222"
  },
  "second": {
    "aaa": "111",
    "bbb": "2222"
  }
}

I've then tried a few a number of ways to loop through this data as follows but not work as expected:

{Object.keys(data).map((key, value) =>
    console.log(key);
    <li>{value.aaa}</li>
)}

I can console.log out the data and see it loops but I can't see to display the aaa or bbb values.

What am I doing wrong here?

Upvotes: 4

Views: 4951

Answers (4)

Alejandro Lasebnik
Alejandro Lasebnik

Reputation: 874

I succeeded to run your code. It was basically ok, just need to change the property name "key" from .map since it conflicts with a react keyword.

 {Object.keys(data).map((label, index) => (
                <div key={index}>{data[label].aaa}</div>
            ))}

Upvotes: 0

B.Shrestha
B.Shrestha

Reputation: 136

try using

{Object.keys(data).map((key, index) =>
    <li key={index}>{data[key].aaa}</li>
)}

Upvotes: 1

Govind Rai
Govind Rai

Reputation: 15780

Use a for in loop:

{for (key in data) {
    for (innerKey in data[key]) {
        <li>{data[key][innerKey]}</li>
    }
}}

The reason we need to use brackets around key and innerKey is because those properties will need to be computed first.

Upvotes: 1

Harsh Makadia
Harsh Makadia

Reputation: 3433

You can assign a variable that holds value.

var a = {
  "first": {
  "aaa": "111",
  "bbb": "2222"
},
"second": {
 "aaa": "111",
 "bbb": "2222"
 }
}

use following to get the keys :

 var keys = Object.keys(a); 

Finally iterate over it :

for(var i = 0; i < keys.length; i++) { 
    var key = (keys[i]) ; 
    console.log(a[key]) 
}

Upvotes: 1

Related Questions