user1212520 user1212520 - 6 months ago 9
JSON Question

Structuring a JSON object

I have a JSON object say:

{
[
{
'name':'personA',
'age':'30',
'description':'some-text'
},
{
'name':'personB',
'age':'40',
'description':'some-text'
}
]
}


This issue is I need to be able to access each var by name, for Example:

people.PersonA.age:


so Instead:

people =

{
'personA':{
'age':'30',
'description':'some-text'
},
'personB':{
'age':'40',
'description':'some-text'
}
}


But then I cannot generate a list of names

What would be the best structure for this? I need to be able to loop though the names and quickly access the age etc using the name as a key

Answer

What about this way of listing all names?

var people = {
  'personA': {'age': '30', 'description': 'some-text'}, 
  'personB': {'age': '40', 'description': 'some-text'}
};

Object.keys(people).forEach(function(name) {
   console.log(name);
});

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach