JS: Find object by field in a complex Parent-Child Array











up vote
2
down vote

favorite












I use Javascript ES6 and have an issue. Hope your guys help me.



I have an Array:



var commentList = [
{'id': 1, text: 'A', children: [{'id': 2, text: 'B' }] },
{'id': 4, text: 'asd', children: },
{'id': 5, text: 'vx', children: [{'id': 7, text: 'xxss' }] },
{'id': 8, text: 'ghfdh', children: [{'id': 15, text: 'I want to take this' }] },
{'id': 10, text: 'A', children: [{'id': 18, text: 'Bsda' }] },
]


This is an Array with Parent - Child Structure. How can I get Exactly object {'id': 15, text: 'I want to take this' } if I just have ID only



I tried but not work



var object = commentList.find(o => o.id === 15) => undefined










share|improve this question






















  • Can those children arrays be nested arbitrarily or is there only a single level?
    – Bergi
    Nov 11 at 11:22










  • Look up recursion
    – Quentin
    Nov 11 at 11:22










  • commentList.concat(...commentList.map(o => o.children)).find(o => o.id == 15) should do it
    – Bergi
    Nov 11 at 11:23















up vote
2
down vote

favorite












I use Javascript ES6 and have an issue. Hope your guys help me.



I have an Array:



var commentList = [
{'id': 1, text: 'A', children: [{'id': 2, text: 'B' }] },
{'id': 4, text: 'asd', children: },
{'id': 5, text: 'vx', children: [{'id': 7, text: 'xxss' }] },
{'id': 8, text: 'ghfdh', children: [{'id': 15, text: 'I want to take this' }] },
{'id': 10, text: 'A', children: [{'id': 18, text: 'Bsda' }] },
]


This is an Array with Parent - Child Structure. How can I get Exactly object {'id': 15, text: 'I want to take this' } if I just have ID only



I tried but not work



var object = commentList.find(o => o.id === 15) => undefined










share|improve this question






















  • Can those children arrays be nested arbitrarily or is there only a single level?
    – Bergi
    Nov 11 at 11:22










  • Look up recursion
    – Quentin
    Nov 11 at 11:22










  • commentList.concat(...commentList.map(o => o.children)).find(o => o.id == 15) should do it
    – Bergi
    Nov 11 at 11:23













up vote
2
down vote

favorite









up vote
2
down vote

favorite











I use Javascript ES6 and have an issue. Hope your guys help me.



I have an Array:



var commentList = [
{'id': 1, text: 'A', children: [{'id': 2, text: 'B' }] },
{'id': 4, text: 'asd', children: },
{'id': 5, text: 'vx', children: [{'id': 7, text: 'xxss' }] },
{'id': 8, text: 'ghfdh', children: [{'id': 15, text: 'I want to take this' }] },
{'id': 10, text: 'A', children: [{'id': 18, text: 'Bsda' }] },
]


This is an Array with Parent - Child Structure. How can I get Exactly object {'id': 15, text: 'I want to take this' } if I just have ID only



I tried but not work



var object = commentList.find(o => o.id === 15) => undefined










share|improve this question













I use Javascript ES6 and have an issue. Hope your guys help me.



I have an Array:



var commentList = [
{'id': 1, text: 'A', children: [{'id': 2, text: 'B' }] },
{'id': 4, text: 'asd', children: },
{'id': 5, text: 'vx', children: [{'id': 7, text: 'xxss' }] },
{'id': 8, text: 'ghfdh', children: [{'id': 15, text: 'I want to take this' }] },
{'id': 10, text: 'A', children: [{'id': 18, text: 'Bsda' }] },
]


This is an Array with Parent - Child Structure. How can I get Exactly object {'id': 15, text: 'I want to take this' } if I just have ID only



I tried but not work



var object = commentList.find(o => o.id === 15) => undefined







javascript ecmascript-6






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 11 at 11:20









Feed Git

698826




698826












  • Can those children arrays be nested arbitrarily or is there only a single level?
    – Bergi
    Nov 11 at 11:22










  • Look up recursion
    – Quentin
    Nov 11 at 11:22










  • commentList.concat(...commentList.map(o => o.children)).find(o => o.id == 15) should do it
    – Bergi
    Nov 11 at 11:23


















  • Can those children arrays be nested arbitrarily or is there only a single level?
    – Bergi
    Nov 11 at 11:22










  • Look up recursion
    – Quentin
    Nov 11 at 11:22










  • commentList.concat(...commentList.map(o => o.children)).find(o => o.id == 15) should do it
    – Bergi
    Nov 11 at 11:23
















Can those children arrays be nested arbitrarily or is there only a single level?
– Bergi
Nov 11 at 11:22




Can those children arrays be nested arbitrarily or is there only a single level?
– Bergi
Nov 11 at 11:22












Look up recursion
– Quentin
Nov 11 at 11:22




Look up recursion
– Quentin
Nov 11 at 11:22












commentList.concat(...commentList.map(o => o.children)).find(o => o.id == 15) should do it
– Bergi
Nov 11 at 11:23




commentList.concat(...commentList.map(o => o.children)).find(o => o.id == 15) should do it
– Bergi
Nov 11 at 11:23












4 Answers
4






active

oldest

votes

















up vote
2
down vote













You could take an iterative and recursive approach by checking the id or taking the children.






const find = (array, id) => {
var result;
array.some(o => result = o.id === id ? o : find(o.children || , id));
return result;
};

var commentList = [{ id: 1, text: 'A', children: [{ id: 2, text: 'B' }] }, { id: 4, text: 'asd', children: }, { id: 5, text: 'vx', children: [{ id: 7, text: 'xxss' }] }, { id: 8, text: 'ghfdh', children: [{ id: 15, text: 'I want to take this' }] }, { id: 10, text: 'A', children: [{ id: 18, text: 'Bsda' }] }];

console.log(find(commentList, 15));








share|improve this answer




























    up vote
    1
    down vote













    I would extract the logic into a function and then iterate over the children array and return the one you requested (The first match).






    var commentList = [
    {'id': 1, text: 'A', children: [{'id': 2, text: 'B' }] },
    {'id': 4, text: 'asd', children: },
    {'id': 5, text: 'vx', children: [{'id': 7, text: 'xxss' }] },
    {'id': 8, text: 'ghfdh', children: [{'id': 15, text: 'I want to take this' }] },
    {'id': 10, text: 'A', children: [{'id': 18, text: 'Bsda' }] },
    ]

    const findChildById = (id, arr) => {
    const result = arr.find(o => o.id === id)
    if (result) return result
    for (const cm of arr) {
    const result = cm.children.find(o => o.id === id)
    if (result) return result
    }
    }
    console.log(findChildById(10, commentList))








    share|improve this answer























    • …assuming that you already know that the id you have belongs to a child object
      – Bergi
      Nov 11 at 11:28










    • @Bergi, what do you mean? The OP said he wants to search the children array. If the id does not exist than a custom string is returned
      – omri_saadon
      Nov 11 at 11:59












    • The OP never said that he wants to search only the children arrays or that he wants to find a child.
      – Bergi
      Nov 11 at 12:13










    • @Bergi, I see, Thanks for noticing. I've updated the code for finding in parent and only than finding in children.
      – omri_saadon
      Nov 11 at 12:26


















    up vote
    1
    down vote













    You can use for...of to find the find the item recursively. If there's no item, the function will return undefined:






    const find = (array = , id) => {
    for (const item of array) {
    const result = item.id === id ? item : find(item.children, id);
    if(result) return result;
    }
    };

    const commentList = [{ id: 1, text: 'A', children: [{ id: 2, text: 'B' }] }, { id: 4, text: 'asd', children: }, { id: 5, text: 'vx', children: [{ id: 7, text: 'xxss' }] }, { id: 8, text: 'ghfdh', children: [{ id: 15, text: 'I want to take this' }] }, { id: 10, text: 'A', children: [{ id: 18, text: 'Bsda' }] }];

    const result = find(commentList, 15);

    console.log(result);








    share|improve this answer




























      up vote
      1
      down vote













      Following very simple and basic code should work for you. I assume that all id-s of all children elements in all arrays are unique. This code will find the first element that matches the id we are looking for;



      var result = null;
      var idToSearch = 15;
      var i=0;
      var j=0;

      for(i=0; i<commentList.length; i++){
      var currentChildren = commentList[i].children;
      if(currentChildren && currentChildren.length > 0){
      for(j=0; j<currentChildren.length; j++){
      if(currentChildren[j].id === idToSearch){
      result=currentChildren[j];
      j=currentChildren.length;
      i=commentList.length;
      }
      }
      }
      }





      share|improve this answer





















        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53248202%2fjs-find-object-by-field-in-a-complex-parent-child-array%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        4 Answers
        4






        active

        oldest

        votes








        4 Answers
        4






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes








        up vote
        2
        down vote













        You could take an iterative and recursive approach by checking the id or taking the children.






        const find = (array, id) => {
        var result;
        array.some(o => result = o.id === id ? o : find(o.children || , id));
        return result;
        };

        var commentList = [{ id: 1, text: 'A', children: [{ id: 2, text: 'B' }] }, { id: 4, text: 'asd', children: }, { id: 5, text: 'vx', children: [{ id: 7, text: 'xxss' }] }, { id: 8, text: 'ghfdh', children: [{ id: 15, text: 'I want to take this' }] }, { id: 10, text: 'A', children: [{ id: 18, text: 'Bsda' }] }];

        console.log(find(commentList, 15));








        share|improve this answer

























          up vote
          2
          down vote













          You could take an iterative and recursive approach by checking the id or taking the children.






          const find = (array, id) => {
          var result;
          array.some(o => result = o.id === id ? o : find(o.children || , id));
          return result;
          };

          var commentList = [{ id: 1, text: 'A', children: [{ id: 2, text: 'B' }] }, { id: 4, text: 'asd', children: }, { id: 5, text: 'vx', children: [{ id: 7, text: 'xxss' }] }, { id: 8, text: 'ghfdh', children: [{ id: 15, text: 'I want to take this' }] }, { id: 10, text: 'A', children: [{ id: 18, text: 'Bsda' }] }];

          console.log(find(commentList, 15));








          share|improve this answer























            up vote
            2
            down vote










            up vote
            2
            down vote









            You could take an iterative and recursive approach by checking the id or taking the children.






            const find = (array, id) => {
            var result;
            array.some(o => result = o.id === id ? o : find(o.children || , id));
            return result;
            };

            var commentList = [{ id: 1, text: 'A', children: [{ id: 2, text: 'B' }] }, { id: 4, text: 'asd', children: }, { id: 5, text: 'vx', children: [{ id: 7, text: 'xxss' }] }, { id: 8, text: 'ghfdh', children: [{ id: 15, text: 'I want to take this' }] }, { id: 10, text: 'A', children: [{ id: 18, text: 'Bsda' }] }];

            console.log(find(commentList, 15));








            share|improve this answer












            You could take an iterative and recursive approach by checking the id or taking the children.






            const find = (array, id) => {
            var result;
            array.some(o => result = o.id === id ? o : find(o.children || , id));
            return result;
            };

            var commentList = [{ id: 1, text: 'A', children: [{ id: 2, text: 'B' }] }, { id: 4, text: 'asd', children: }, { id: 5, text: 'vx', children: [{ id: 7, text: 'xxss' }] }, { id: 8, text: 'ghfdh', children: [{ id: 15, text: 'I want to take this' }] }, { id: 10, text: 'A', children: [{ id: 18, text: 'Bsda' }] }];

            console.log(find(commentList, 15));








            const find = (array, id) => {
            var result;
            array.some(o => result = o.id === id ? o : find(o.children || , id));
            return result;
            };

            var commentList = [{ id: 1, text: 'A', children: [{ id: 2, text: 'B' }] }, { id: 4, text: 'asd', children: }, { id: 5, text: 'vx', children: [{ id: 7, text: 'xxss' }] }, { id: 8, text: 'ghfdh', children: [{ id: 15, text: 'I want to take this' }] }, { id: 10, text: 'A', children: [{ id: 18, text: 'Bsda' }] }];

            console.log(find(commentList, 15));





            const find = (array, id) => {
            var result;
            array.some(o => result = o.id === id ? o : find(o.children || , id));
            return result;
            };

            var commentList = [{ id: 1, text: 'A', children: [{ id: 2, text: 'B' }] }, { id: 4, text: 'asd', children: }, { id: 5, text: 'vx', children: [{ id: 7, text: 'xxss' }] }, { id: 8, text: 'ghfdh', children: [{ id: 15, text: 'I want to take this' }] }, { id: 10, text: 'A', children: [{ id: 18, text: 'Bsda' }] }];

            console.log(find(commentList, 15));






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 11 at 11:28









            Nina Scholz

            171k1383147




            171k1383147
























                up vote
                1
                down vote













                I would extract the logic into a function and then iterate over the children array and return the one you requested (The first match).






                var commentList = [
                {'id': 1, text: 'A', children: [{'id': 2, text: 'B' }] },
                {'id': 4, text: 'asd', children: },
                {'id': 5, text: 'vx', children: [{'id': 7, text: 'xxss' }] },
                {'id': 8, text: 'ghfdh', children: [{'id': 15, text: 'I want to take this' }] },
                {'id': 10, text: 'A', children: [{'id': 18, text: 'Bsda' }] },
                ]

                const findChildById = (id, arr) => {
                const result = arr.find(o => o.id === id)
                if (result) return result
                for (const cm of arr) {
                const result = cm.children.find(o => o.id === id)
                if (result) return result
                }
                }
                console.log(findChildById(10, commentList))








                share|improve this answer























                • …assuming that you already know that the id you have belongs to a child object
                  – Bergi
                  Nov 11 at 11:28










                • @Bergi, what do you mean? The OP said he wants to search the children array. If the id does not exist than a custom string is returned
                  – omri_saadon
                  Nov 11 at 11:59












                • The OP never said that he wants to search only the children arrays or that he wants to find a child.
                  – Bergi
                  Nov 11 at 12:13










                • @Bergi, I see, Thanks for noticing. I've updated the code for finding in parent and only than finding in children.
                  – omri_saadon
                  Nov 11 at 12:26















                up vote
                1
                down vote













                I would extract the logic into a function and then iterate over the children array and return the one you requested (The first match).






                var commentList = [
                {'id': 1, text: 'A', children: [{'id': 2, text: 'B' }] },
                {'id': 4, text: 'asd', children: },
                {'id': 5, text: 'vx', children: [{'id': 7, text: 'xxss' }] },
                {'id': 8, text: 'ghfdh', children: [{'id': 15, text: 'I want to take this' }] },
                {'id': 10, text: 'A', children: [{'id': 18, text: 'Bsda' }] },
                ]

                const findChildById = (id, arr) => {
                const result = arr.find(o => o.id === id)
                if (result) return result
                for (const cm of arr) {
                const result = cm.children.find(o => o.id === id)
                if (result) return result
                }
                }
                console.log(findChildById(10, commentList))








                share|improve this answer























                • …assuming that you already know that the id you have belongs to a child object
                  – Bergi
                  Nov 11 at 11:28










                • @Bergi, what do you mean? The OP said he wants to search the children array. If the id does not exist than a custom string is returned
                  – omri_saadon
                  Nov 11 at 11:59












                • The OP never said that he wants to search only the children arrays or that he wants to find a child.
                  – Bergi
                  Nov 11 at 12:13










                • @Bergi, I see, Thanks for noticing. I've updated the code for finding in parent and only than finding in children.
                  – omri_saadon
                  Nov 11 at 12:26













                up vote
                1
                down vote










                up vote
                1
                down vote









                I would extract the logic into a function and then iterate over the children array and return the one you requested (The first match).






                var commentList = [
                {'id': 1, text: 'A', children: [{'id': 2, text: 'B' }] },
                {'id': 4, text: 'asd', children: },
                {'id': 5, text: 'vx', children: [{'id': 7, text: 'xxss' }] },
                {'id': 8, text: 'ghfdh', children: [{'id': 15, text: 'I want to take this' }] },
                {'id': 10, text: 'A', children: [{'id': 18, text: 'Bsda' }] },
                ]

                const findChildById = (id, arr) => {
                const result = arr.find(o => o.id === id)
                if (result) return result
                for (const cm of arr) {
                const result = cm.children.find(o => o.id === id)
                if (result) return result
                }
                }
                console.log(findChildById(10, commentList))








                share|improve this answer














                I would extract the logic into a function and then iterate over the children array and return the one you requested (The first match).






                var commentList = [
                {'id': 1, text: 'A', children: [{'id': 2, text: 'B' }] },
                {'id': 4, text: 'asd', children: },
                {'id': 5, text: 'vx', children: [{'id': 7, text: 'xxss' }] },
                {'id': 8, text: 'ghfdh', children: [{'id': 15, text: 'I want to take this' }] },
                {'id': 10, text: 'A', children: [{'id': 18, text: 'Bsda' }] },
                ]

                const findChildById = (id, arr) => {
                const result = arr.find(o => o.id === id)
                if (result) return result
                for (const cm of arr) {
                const result = cm.children.find(o => o.id === id)
                if (result) return result
                }
                }
                console.log(findChildById(10, commentList))








                var commentList = [
                {'id': 1, text: 'A', children: [{'id': 2, text: 'B' }] },
                {'id': 4, text: 'asd', children: },
                {'id': 5, text: 'vx', children: [{'id': 7, text: 'xxss' }] },
                {'id': 8, text: 'ghfdh', children: [{'id': 15, text: 'I want to take this' }] },
                {'id': 10, text: 'A', children: [{'id': 18, text: 'Bsda' }] },
                ]

                const findChildById = (id, arr) => {
                const result = arr.find(o => o.id === id)
                if (result) return result
                for (const cm of arr) {
                const result = cm.children.find(o => o.id === id)
                if (result) return result
                }
                }
                console.log(findChildById(10, commentList))





                var commentList = [
                {'id': 1, text: 'A', children: [{'id': 2, text: 'B' }] },
                {'id': 4, text: 'asd', children: },
                {'id': 5, text: 'vx', children: [{'id': 7, text: 'xxss' }] },
                {'id': 8, text: 'ghfdh', children: [{'id': 15, text: 'I want to take this' }] },
                {'id': 10, text: 'A', children: [{'id': 18, text: 'Bsda' }] },
                ]

                const findChildById = (id, arr) => {
                const result = arr.find(o => o.id === id)
                if (result) return result
                for (const cm of arr) {
                const result = cm.children.find(o => o.id === id)
                if (result) return result
                }
                }
                console.log(findChildById(10, commentList))






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 11 at 12:25

























                answered Nov 11 at 11:26









                omri_saadon

                6,94831444




                6,94831444












                • …assuming that you already know that the id you have belongs to a child object
                  – Bergi
                  Nov 11 at 11:28










                • @Bergi, what do you mean? The OP said he wants to search the children array. If the id does not exist than a custom string is returned
                  – omri_saadon
                  Nov 11 at 11:59












                • The OP never said that he wants to search only the children arrays or that he wants to find a child.
                  – Bergi
                  Nov 11 at 12:13










                • @Bergi, I see, Thanks for noticing. I've updated the code for finding in parent and only than finding in children.
                  – omri_saadon
                  Nov 11 at 12:26


















                • …assuming that you already know that the id you have belongs to a child object
                  – Bergi
                  Nov 11 at 11:28










                • @Bergi, what do you mean? The OP said he wants to search the children array. If the id does not exist than a custom string is returned
                  – omri_saadon
                  Nov 11 at 11:59












                • The OP never said that he wants to search only the children arrays or that he wants to find a child.
                  – Bergi
                  Nov 11 at 12:13










                • @Bergi, I see, Thanks for noticing. I've updated the code for finding in parent and only than finding in children.
                  – omri_saadon
                  Nov 11 at 12:26
















                …assuming that you already know that the id you have belongs to a child object
                – Bergi
                Nov 11 at 11:28




                …assuming that you already know that the id you have belongs to a child object
                – Bergi
                Nov 11 at 11:28












                @Bergi, what do you mean? The OP said he wants to search the children array. If the id does not exist than a custom string is returned
                – omri_saadon
                Nov 11 at 11:59






                @Bergi, what do you mean? The OP said he wants to search the children array. If the id does not exist than a custom string is returned
                – omri_saadon
                Nov 11 at 11:59














                The OP never said that he wants to search only the children arrays or that he wants to find a child.
                – Bergi
                Nov 11 at 12:13




                The OP never said that he wants to search only the children arrays or that he wants to find a child.
                – Bergi
                Nov 11 at 12:13












                @Bergi, I see, Thanks for noticing. I've updated the code for finding in parent and only than finding in children.
                – omri_saadon
                Nov 11 at 12:26




                @Bergi, I see, Thanks for noticing. I've updated the code for finding in parent and only than finding in children.
                – omri_saadon
                Nov 11 at 12:26










                up vote
                1
                down vote













                You can use for...of to find the find the item recursively. If there's no item, the function will return undefined:






                const find = (array = , id) => {
                for (const item of array) {
                const result = item.id === id ? item : find(item.children, id);
                if(result) return result;
                }
                };

                const commentList = [{ id: 1, text: 'A', children: [{ id: 2, text: 'B' }] }, { id: 4, text: 'asd', children: }, { id: 5, text: 'vx', children: [{ id: 7, text: 'xxss' }] }, { id: 8, text: 'ghfdh', children: [{ id: 15, text: 'I want to take this' }] }, { id: 10, text: 'A', children: [{ id: 18, text: 'Bsda' }] }];

                const result = find(commentList, 15);

                console.log(result);








                share|improve this answer

























                  up vote
                  1
                  down vote













                  You can use for...of to find the find the item recursively. If there's no item, the function will return undefined:






                  const find = (array = , id) => {
                  for (const item of array) {
                  const result = item.id === id ? item : find(item.children, id);
                  if(result) return result;
                  }
                  };

                  const commentList = [{ id: 1, text: 'A', children: [{ id: 2, text: 'B' }] }, { id: 4, text: 'asd', children: }, { id: 5, text: 'vx', children: [{ id: 7, text: 'xxss' }] }, { id: 8, text: 'ghfdh', children: [{ id: 15, text: 'I want to take this' }] }, { id: 10, text: 'A', children: [{ id: 18, text: 'Bsda' }] }];

                  const result = find(commentList, 15);

                  console.log(result);








                  share|improve this answer























                    up vote
                    1
                    down vote










                    up vote
                    1
                    down vote









                    You can use for...of to find the find the item recursively. If there's no item, the function will return undefined:






                    const find = (array = , id) => {
                    for (const item of array) {
                    const result = item.id === id ? item : find(item.children, id);
                    if(result) return result;
                    }
                    };

                    const commentList = [{ id: 1, text: 'A', children: [{ id: 2, text: 'B' }] }, { id: 4, text: 'asd', children: }, { id: 5, text: 'vx', children: [{ id: 7, text: 'xxss' }] }, { id: 8, text: 'ghfdh', children: [{ id: 15, text: 'I want to take this' }] }, { id: 10, text: 'A', children: [{ id: 18, text: 'Bsda' }] }];

                    const result = find(commentList, 15);

                    console.log(result);








                    share|improve this answer












                    You can use for...of to find the find the item recursively. If there's no item, the function will return undefined:






                    const find = (array = , id) => {
                    for (const item of array) {
                    const result = item.id === id ? item : find(item.children, id);
                    if(result) return result;
                    }
                    };

                    const commentList = [{ id: 1, text: 'A', children: [{ id: 2, text: 'B' }] }, { id: 4, text: 'asd', children: }, { id: 5, text: 'vx', children: [{ id: 7, text: 'xxss' }] }, { id: 8, text: 'ghfdh', children: [{ id: 15, text: 'I want to take this' }] }, { id: 10, text: 'A', children: [{ id: 18, text: 'Bsda' }] }];

                    const result = find(commentList, 15);

                    console.log(result);








                    const find = (array = , id) => {
                    for (const item of array) {
                    const result = item.id === id ? item : find(item.children, id);
                    if(result) return result;
                    }
                    };

                    const commentList = [{ id: 1, text: 'A', children: [{ id: 2, text: 'B' }] }, { id: 4, text: 'asd', children: }, { id: 5, text: 'vx', children: [{ id: 7, text: 'xxss' }] }, { id: 8, text: 'ghfdh', children: [{ id: 15, text: 'I want to take this' }] }, { id: 10, text: 'A', children: [{ id: 18, text: 'Bsda' }] }];

                    const result = find(commentList, 15);

                    console.log(result);





                    const find = (array = , id) => {
                    for (const item of array) {
                    const result = item.id === id ? item : find(item.children, id);
                    if(result) return result;
                    }
                    };

                    const commentList = [{ id: 1, text: 'A', children: [{ id: 2, text: 'B' }] }, { id: 4, text: 'asd', children: }, { id: 5, text: 'vx', children: [{ id: 7, text: 'xxss' }] }, { id: 8, text: 'ghfdh', children: [{ id: 15, text: 'I want to take this' }] }, { id: 10, text: 'A', children: [{ id: 18, text: 'Bsda' }] }];

                    const result = find(commentList, 15);

                    console.log(result);






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 11 at 18:34









                    Ori Drori

                    71.4k127489




                    71.4k127489






















                        up vote
                        1
                        down vote













                        Following very simple and basic code should work for you. I assume that all id-s of all children elements in all arrays are unique. This code will find the first element that matches the id we are looking for;



                        var result = null;
                        var idToSearch = 15;
                        var i=0;
                        var j=0;

                        for(i=0; i<commentList.length; i++){
                        var currentChildren = commentList[i].children;
                        if(currentChildren && currentChildren.length > 0){
                        for(j=0; j<currentChildren.length; j++){
                        if(currentChildren[j].id === idToSearch){
                        result=currentChildren[j];
                        j=currentChildren.length;
                        i=commentList.length;
                        }
                        }
                        }
                        }





                        share|improve this answer

























                          up vote
                          1
                          down vote













                          Following very simple and basic code should work for you. I assume that all id-s of all children elements in all arrays are unique. This code will find the first element that matches the id we are looking for;



                          var result = null;
                          var idToSearch = 15;
                          var i=0;
                          var j=0;

                          for(i=0; i<commentList.length; i++){
                          var currentChildren = commentList[i].children;
                          if(currentChildren && currentChildren.length > 0){
                          for(j=0; j<currentChildren.length; j++){
                          if(currentChildren[j].id === idToSearch){
                          result=currentChildren[j];
                          j=currentChildren.length;
                          i=commentList.length;
                          }
                          }
                          }
                          }





                          share|improve this answer























                            up vote
                            1
                            down vote










                            up vote
                            1
                            down vote









                            Following very simple and basic code should work for you. I assume that all id-s of all children elements in all arrays are unique. This code will find the first element that matches the id we are looking for;



                            var result = null;
                            var idToSearch = 15;
                            var i=0;
                            var j=0;

                            for(i=0; i<commentList.length; i++){
                            var currentChildren = commentList[i].children;
                            if(currentChildren && currentChildren.length > 0){
                            for(j=0; j<currentChildren.length; j++){
                            if(currentChildren[j].id === idToSearch){
                            result=currentChildren[j];
                            j=currentChildren.length;
                            i=commentList.length;
                            }
                            }
                            }
                            }





                            share|improve this answer












                            Following very simple and basic code should work for you. I assume that all id-s of all children elements in all arrays are unique. This code will find the first element that matches the id we are looking for;



                            var result = null;
                            var idToSearch = 15;
                            var i=0;
                            var j=0;

                            for(i=0; i<commentList.length; i++){
                            var currentChildren = commentList[i].children;
                            if(currentChildren && currentChildren.length > 0){
                            for(j=0; j<currentChildren.length; j++){
                            if(currentChildren[j].id === idToSearch){
                            result=currentChildren[j];
                            j=currentChildren.length;
                            i=commentList.length;
                            }
                            }
                            }
                            }






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 11 at 18:54









                            Tornike Shavishvili

                            60311022




                            60311022






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.





                                Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                Please pay close attention to the following guidance:


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53248202%2fjs-find-object-by-field-in-a-complex-parent-child-array%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                List item for chat from Array inside array React Native

                                Thiostrepton

                                Caerphilly