Proximo Proximo - 6 months ago 12
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=> == 'Susan');
var childQuery = parents.filter(parent=> == 'Joe');
var parentChildQuery = parents.filter(parent=> == 'Susan' && == '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. == 'Joe'

Any help would be greatly appreciated!


.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 => == 'Joe'));
parents.filter(parent => parent.children.some(child => == 'Joe'));