I would like to search by specific key on nested array/ object on javascript and need to return all hierarchy structure, include it's parent until root parent and also it's child. Here is the sample json:
let array = [
{
"no": "1",
"name": "abc",
"child" : [
{
"no": "1.1",
"name": "def",
"child" : [
{
"no": "1.1.1",
"name": "Foo"
},
{
"no": "1.1.2",
"name": "jkl"
}
]
},
{
"no": "1.2",
"name": "Foo",
"child" : [
{
"no": "1.2.1",
"name": "Foo"
},
{
"no": "1.2.2",
"name": "aaaaaaa"
}
]
}
]
},
{
"no": "2",
"name": "abc2",
"child" : [
{
"no": "2.1",
"name": "Foo",
"child" : [
{
"no": "1.1.1",
"name": "ghi"
},
{
"no": "1.1.2",
"name": "jkl"
}
]
},
{
"no": "2.2",
"name": "ghssssi",
"child" : [
{
"no": "2.2.1",
"name": "ghssssi"
},
{
"no": "2.2.2",
"name": "asass"
}
]
}
]
}
];
And when we want to search by key ='Foo', the result would be something like this:
array_result = [
{
"no": "1",
"name": "abc",
"child" : [
{
"no": "1.1",
"name": "def",
"child" : [
{
"no": "1.1.1",
"name": "Foo"
}
]
},
{
"no": "1.2",
"name": "Foo",
"child" : [
{
"no": "1.2.1",
"name": "Foo"
}
]
}
]
},
{
"no": "2",
"name": "abc2",
"child" : [
{
"no": "2.1",
"name": "Foo",
"child" : [
{
"no": "1.1.1",
"name": "ghi"
},
{
"no": "1.1.2",
"name": "jkl"
}
]
}
]
}
];
I'm sure it will need recursive function. Anyone got idea? Thanks!
You could take a copy from the original array and filter the array, if it has the wanted value or the children have the value.
var array = [{ no: "1", name: "abc", children: [{ no: "1.1", name: "def", children: [{ no: "1.1.1", name: "Foo" }, { no: "1.1.2", name: "jkl" }] }, { no: "1.2", name: "Foo", children: [{ no: "1.2.1", name: "Foo" }, { no: "1.2.2", name: "aaaaaaa" }] }] }, { no: "2", name: "abc2", children: [{ no: "2.1", name: "Foo", children: [{ no: "1.1.1", name: "ghi" }, { no: "1.1.2", name: "jkl" }] }, { no: "2.2", name: "ghssssi", children: [{ no: "2.2.1", name: "ghssssi" }, { no: "2.2.2", name: "asass" }] }] }],
find = 'Foo',
result = JSON.parse(JSON.stringify(array)).filter(function search(a) {
var children;
if (a.name === find) {
return true;
}
if (!Array.isArray(a.children)) {
return false;
}
children = a.children.filter(search);
if (children.length) {
a.children = children;
return true;
}
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }