0
let tree = {
    name: "A",
    children: [
        {
            name: 'A-1',
            children: [
                {name: "A-1-A"},
                {name: "A-1-B"},
            ]
        },
        {
            name: 'B-1',
            children: [
                {
                    name: "B-1-A",
                    children: [
                        {name: "B-11-A"},
                        {name: "B-11-B"}
                    ]
                },
                {name: "B-1-B"},
            ]
        },

    ]


};

how to get sub object from a big object .In my problem I have a big object and search text I want to get whole object which have name property is equal to searchtext

I tried like this

 function searchObj(obj,searchText){
        if(obj.name === searchText) return obj;
        let result;
            if(obj['children'] && obj['children'].length > 0){
                obj['children'].forEach((i)=>{
                   result =searchObj(i,searchText)
                })
            }
        return result || null
    }

    console.log(searchObj(tree,'A-1'))

getting output null

expected output

{
            name: 'A-1',
            children: [
                {name: "A-1-A"},
                {name: "A-1-B"},
            ]
        }

I used recursion to get the object but I am not sure why is not working

1 Answers1

0

no need to define a variable inside the function

const tree = { name: "A", children: [ { name: 'A-1', children: [ {name: "A-1-A"}, {name: "A-1-B"}, ] }, { name: 'B-1', children: [ { name: "B-1-A", children: [ {name: "B-11-A"}, {name: "B-11-B"} ] }, {name: "B-1-B"}, ] },]};


function searchObj(obj,searchText){
        if(obj.name === searchText) return obj;
            if(obj['children'] && obj['children'].length > 0){
                obj['children'].forEach((i)=>{
                   result =searchObj(i,searchText)
                })
            }
        return result 
    }

    console.log(searchObj(tree,'A-1'))
prasanth
  • 22,145
  • 4
  • 29
  • 53