RJacob41 RJacob41 -4 years ago 69
jQuery Question

Get a list of objects at each nested level

{
"John Doe": {
"Age": 18,
"Gender": "M"
},
"Jane Doe": {
"Age": 16,
"Gender": "F"
},
"Steve Appleseed":{
"Age": 21,
"Gender": "M"
}
}


Using JavaScript, how do I get an array

var names = ["John Doe", "Jane Doe", "Steve Appleseed"];


If it helps, I'm using Firebase with a JavaScript and jQuery PWA, and I need a list of all the names of objects at a nesting particular level.

Answer Source

Firstly note that this has nothing to do with JSON. What you have is an object. Therefore Object.keys will do what you require:

var obj = {
  "John Doe": {
    "Age": 18,
    "Gender": "M"
  },
  "Jane Doe": {
    "Age": 16,
    "Gender": "F"
  },
  "Steve Appleseed": {
    "Age": 21,
    "Gender": "M"
  }
}

var keys = Object.keys(obj);
console.log(keys);

console.log(obj[keys[0]]["Age"]); // John Doe's age

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download