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!
-
1What have you tried yourself so far? Show us your code so someone can point out the problem. This is not the place to get complete code answers.MeanGreen– MeanGreen2016年12月30日 09:45:07 +00:00Commented Dec 30, 2016 at 9:45
-
would you like to get a copy of the original data without mutating the original?Nina Scholz– Nina Scholz2016年12月30日 10:04:11 +00:00Commented Dec 30, 2016 at 10:04
1 Answer 1
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; }
answered Dec 30, 2016 at 10:13
Nina Scholz
388k26 gold badges367 silver badges417 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
ipeh
thanks @nina, it helped me a lot. I've modified the code based on my need.
lang-js