Proximo Proximo - 4 months ago 7
Javascript Question

Querying JavaScript Parent Child object

I have a json object that shows parent children relationships.

I find it very difficult to query for a certain child.

For example here's the data.

var parents = [
{
name: 'Susan',
children: [{
name: 'Joe'
}, {
name: 'Sam'
}, {
name: 'Michael'
}]
},
{
name: 'Ted',
children: [{
name: 'Richard'
}, {
name: 'Brad'
}]
}
]


In an elegant way I'd like to be able to find the object based on parent name and child name.

Parent: Susan
Child: Joe

Here's how I'd do the 3 types of queries I'm trying to do in C#

var parentQuery = parents.filter(parent=> parent.name == 'Susan');
var childQuery = parents.filter(parent=> parent.children.name == 'Joe');
var parentChildQuery = parents.filter(parent=> parent.name == 'Susan' && parent.children.name == 'Joe')


The parentQuery works out of the box in Javascript to my delight. But the childQuery search doesn't work. Since parent has an internal array I'm not sure how to reference to query on a property. Shown below.


parent.children.name == 'Joe'


Any help would be greatly appreciated!

Answer

.children is an array and doesn't have a .name property. Maybe you meant one of

parents.filter(parent => parent.children[0].name == 'Joe');
parents.filter(parent => parent.children.every(child => child.name == 'Joe'));
parents.filter(parent => parent.children.some(child => child.name == 'Joe'));