Jasmin Jasmin - 5 months ago 6
JSON Question

How to access specific value from a nested array within an object array?

I am trying to get a specific field value from a nested array within an object array. I'm assuming I'd use map, but every time I use it in this way I get two empty arrays nested inside two empty objects. I know this is wrong, I'm just showing where my thinking process is going.

function getChildArray(item, index) {
var x = [item.hobbies]
return x
}

console.log(parentArray.map(getChildArray))


This is an example of my document structure:

[
{
"id":12345678900,
"name":"Jasmin",
"age":27,
"hobbies":[
{
"id":1221,
"name":"hiking",
"when":"anytime"
},
{
"id":9865,
"name":"eating",
"when":"all the time"
}
]
},
{
"id":223456789001,
"name":"Joe",
"age":35,
"hobbies":[
{
"id":989,
"name":"gaming",
"when":"anytime"
},
{
"id":2355,
"name":"online gaming",
"when":"all the time"
}
]
}
]


How would I, for example, be able to retrieve a list of Joe's hobbies by name only?

Answer
var joe = parentArray.find(function (item) {
    return item.name === 'Joe';
});

if (joe) {
    var joesHobbiesNames = joe.hobbies.map(function (hobbie) {
       return hobbie.name;
    });
}

Or in ES6

var joe = parentArray.find((item) => item.name === 'Joe');

if (joe) {
    var joesHobbiesNames = joe.hobbies.map((hobbie) => hobbie.name);
}