4

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?

1
  • 1
    The second parameter inside map is the index of the element. Change your code to data[key].aaa inside the li element to get the desired value. Commented Sep 7, 2017 at 3:04

4 Answers 4

1

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

Comments

1

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.

Comments

1

try using

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

Comments

0

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>
            ))}

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.