skip to Main Content

I am having trouble parsing these data in React. Can someone help, please?

{

'a':{
'name':'zou',
'age':'23'
},
'b':{
'name':'zaa',
'age':'20'
},
'c':{
'name':'zee',
'age':'21'
}

}

I’m trying to go through each element to get and display their names and age.

3

Answers


  1. You can first get all the keys from the object and then loop over the object keys (in this case [a,b,c]) and get the desired result.

    let data = {
      'a': {
        'name': 'zou',
        'age': '23'
      },
      'b': {
        'name': 'zaa',
        'age': '20'
      },
      'c': {
        'name': 'zee',
        'age': '21'
      }
    }
    
    Object.keys(data).forEach(key => {
      console.log(data[key].name, ' --- ', data[key].age);
    });
    Login or Signup to reply.
    1. Use JSON.parse to convert the JSON into JavaScript Object.
    2. Then use for in loop to loop through each item.
    3. Inside the loop use . or [] to get the specific property.

    Hope it will be helpful.

    Login or Signup to reply.
  2. You can iterate through the heys of this dict (data) and append the needed data in another dict to iterate through in React Component.

    for (let key in data)
    {
    console.log( key, data[key]['name'] )
    console.log( key, data[key]['age'] )
    }
    

    If you can provide the react component code could be an easier way.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search