Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to search a value from a array of objects inside array of objects?

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

like image 623
Vishnu Shenoy Avatar asked Dec 30 '25 12:12

Vishnu Shenoy


1 Answers

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);
like image 150
Nina Scholz Avatar answered Jan 01 '26 02:01

Nina Scholz