I have an array of object, in which each object has an inner array of the object which in turn has again an inner array of objects, it can go to any level of the inner object which I want to filter and display.
obj = [{ name: "apple", subGroups: [{ name: "apple-a", subGroups: { name: "apple-b", subGroups: [{ name: "apple-c", subGroups: { name: "apple-d", subGroups:[]}}]}}]}
{ name: "orange", subGroups: [{ name: "orange-a", subGroups: { name: "orange-b", subGroups: [{ name: "orange-c", subGroups: { name: "orange-d", subGroups:[]}}]}}]}
{ name: "mango", subGroups: [{ name: "123", subGroups: []}]}
{ name: "grapes", subGroups: [{ name: "123", subGroups: []}]}
{ name: "pear", subGroups: [{ name: "123", subGroups: []}]}]
searchvalue is dynamic 'orange-d' ,
searchvalue = 'orange-d';
result = { name: "orange-d", subGroups:[]}
const newArr = obj.map(obj => {
return obj.name === searchvalue;
}).flat();
I have tried with filter, map, flat but I was not able to find the output, pls help
You could take Array#flatMap with a previous check for the handed over array or object, as if follows later as subGroups.
const
find = (array, name) => (Array.isArray(array) ? array : [array])
.flatMap(o => o.name === name ? o : find(o.subGroups, name)),
data = [{ name: "apple", subGroups: [{ name: "apple-a", subGroups: { name: "apple-b", subGroups: [{ name: "apple-c", subGroups: { name: "apple-d", subGroups: [] } }] } }] }, { name: "orange", subGroups: [{ name: "orange-a", subGroups: { name: "orange-b", subGroups: [{ name: "orange-c", subGroups: { name: "orange-d", subGroups: [] } }] } }] }, { name: "mango", subGroups: [{ name: "123", subGroups: [] }] }, { name: "grapes", subGroups: [{ name: "123", subGroups: [] }] }, { name: "pear", subGroups: [{ name: "123", subGroups: [] }] }],
result = find(data, 'orange-d');
console.log(result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With