I have an array of objects that looks like this:
var data = [
{
type: "parent",
children: [
{
type: "parent",
children: [
{
type: "parent"
},
{
type: "parent",
children: [
{
type: "notParent"
},
{
type: "parent"
}
]
}
]
}
]
},
{
type: "parent",
children: [
{
type: "parent"
}
]
},
{
type: "parent",
children: [
{
type: "parent",
children: [
{
type: "parent"
},
{
type: "parent"
}
]
},
{
type: "notParent"
}
]
},
{
type: "notParent"
}
]
This data is an array of objects, and can have objects deeply nested. What I want to do is to create a new array that only contains the objects with the type: "parent" and remove all others. I am finding it hard to make this work for deeply nested objects. I have tried many variations of the following:
var findAllParents = function(obj, type) {
if(obj.type === type) { return obj; }
for(var i in obj) {
if(obj.hasOwnProperty(i)){
var foundParents = findAllParents(obj[i], type);
if(foundParents) { return foundParents; }
}
}
return null;
};
I would like for this to return data like this:
var data = [
{
type: "parent",
children: [
{
type: "parent",
children: [
{
type: "parent"
},
{
type: "parent",
children: [
{
type: "parent"
}
]
}
]
}
]
},
{
type: "parent",
children: [
{
type: "parent"
}
]
},
{
type: "parent",
children: [
{
type: "parent",
children: [
{
type: "parent"
},
{
type: "parent"
}
]
}
]
}
]
Only to return all objects with type: "parent"