Get specific key depth in object with key value The 2019 Stack Overflow Developer Survey Results Are InHow to check the depth of an object?What is the most efficient way to deep clone an object in JavaScript?How can I merge properties of two JavaScript objects dynamically?How do I remove a property from a JavaScript object?endsWith in JavaScriptIs JavaScript a pass-by-reference or pass-by-value language?How can I get query string values in JavaScript?How can I display a JavaScript object?Checking if a key exists in a JavaScript object?Convert form data to JavaScript object with jQueryStoring Objects in HTML5 localStorage

Are USB sockets on wall outlets live all the time, even when the switch is off?

JSON.serialize: is it possible to suppress null values of a map?

Does a dangling wire really electrocute me if I'm standing in water?

"To split hairs" vs "To be pedantic"

"What time...?" or "At what time...?" - what is more grammatically correct?

Geography at the pixel level

Is "plugging out" electronic devices an American expression?

Lethal sonic weapons

Where does the "burst of radiance" from Holy Weapon originate?

Why do UK politicians seemingly ignore opinion polls on Brexit?

aging parents with no investments

Monty Hall variation

How to answer pointed "are you quitting" questioning when I don't want them to suspect

Why is it "Tumoren" and not "Tumore"?

Time travel alters history but people keep saying nothing's changed

What do the Banks children have against barley water?

Springs with some finite mass

How to deal with fear of taking dependencies

Are there any other methods to apply to solving simultaneous equations?

Idiomatic way to prevent slicing?

Why can Shazam do this?

How are circuits which use complex ICs normally simulated?

Pristine Bit Checking

Output the Arecibo Message



Get specific key depth in object with key value



The 2019 Stack Overflow Developer Survey Results Are InHow to check the depth of an object?What is the most efficient way to deep clone an object in JavaScript?How can I merge properties of two JavaScript objects dynamically?How do I remove a property from a JavaScript object?endsWith in JavaScriptIs JavaScript a pass-by-reference or pass-by-value language?How can I get query string values in JavaScript?How can I display a JavaScript object?Checking if a key exists in a JavaScript object?Convert form data to JavaScript object with jQueryStoring Objects in HTML5 localStorage



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















const item = 
id: 'item1',
children: [
id: 'item1-1',
children: [
id: 'item1-1-1' ,
id: 'item1-1-2' ,
id: 'item1-1-3' ,
]
,
id: 'item1-2',
children: [
id: 'item1-2-1'
]

]



Like this,



function getLevelOfId()
...


getLevelOfId('item1') =====> return 1
getLevelOfId('item1-2') =====> return 2
getLevelOfId('item1-1-1') =====> return 3
getLevelOfId('item1-1-2') =====> return 3


How to get specific object's depth with JavaScript?



Not use of id string. like ('item1-2').split('-').length Because each object has randomic id. Is there a simple way?










share|improve this question
























  • Hi! Please take the tour (you get a badge!) and read through the help center, in particular How do I ask a good question? Your best bet here is to do your research, search for related topics on SO, and give it a go. (You'll probably want to use recursion.) If you get stuck and can't get unstuck after doing more research and searching, post a Minimal, Complete, and Verifiable example of your attempt and say specifically where you're stuck. People will be glad to help.

    – T.J. Crowder
    Mar 8 at 8:19












  • Possible duplicate of How to check the depth of an object?

    – Souritra Das Gupta
    Mar 8 at 8:22











  • @SouritraDasGupta It's different. That question is about maximum depth and this is about specific depth.

    – Juntae
    Mar 8 at 9:31

















1















const item = 
id: 'item1',
children: [
id: 'item1-1',
children: [
id: 'item1-1-1' ,
id: 'item1-1-2' ,
id: 'item1-1-3' ,
]
,
id: 'item1-2',
children: [
id: 'item1-2-1'
]

]



Like this,



function getLevelOfId()
...


getLevelOfId('item1') =====> return 1
getLevelOfId('item1-2') =====> return 2
getLevelOfId('item1-1-1') =====> return 3
getLevelOfId('item1-1-2') =====> return 3


How to get specific object's depth with JavaScript?



Not use of id string. like ('item1-2').split('-').length Because each object has randomic id. Is there a simple way?










share|improve this question
























  • Hi! Please take the tour (you get a badge!) and read through the help center, in particular How do I ask a good question? Your best bet here is to do your research, search for related topics on SO, and give it a go. (You'll probably want to use recursion.) If you get stuck and can't get unstuck after doing more research and searching, post a Minimal, Complete, and Verifiable example of your attempt and say specifically where you're stuck. People will be glad to help.

    – T.J. Crowder
    Mar 8 at 8:19












  • Possible duplicate of How to check the depth of an object?

    – Souritra Das Gupta
    Mar 8 at 8:22











  • @SouritraDasGupta It's different. That question is about maximum depth and this is about specific depth.

    – Juntae
    Mar 8 at 9:31













1












1








1


2






const item = 
id: 'item1',
children: [
id: 'item1-1',
children: [
id: 'item1-1-1' ,
id: 'item1-1-2' ,
id: 'item1-1-3' ,
]
,
id: 'item1-2',
children: [
id: 'item1-2-1'
]

]



Like this,



function getLevelOfId()
...


getLevelOfId('item1') =====> return 1
getLevelOfId('item1-2') =====> return 2
getLevelOfId('item1-1-1') =====> return 3
getLevelOfId('item1-1-2') =====> return 3


How to get specific object's depth with JavaScript?



Not use of id string. like ('item1-2').split('-').length Because each object has randomic id. Is there a simple way?










share|improve this question
















const item = 
id: 'item1',
children: [
id: 'item1-1',
children: [
id: 'item1-1-1' ,
id: 'item1-1-2' ,
id: 'item1-1-3' ,
]
,
id: 'item1-2',
children: [
id: 'item1-2-1'
]

]



Like this,



function getLevelOfId()
...


getLevelOfId('item1') =====> return 1
getLevelOfId('item1-2') =====> return 2
getLevelOfId('item1-1-1') =====> return 3
getLevelOfId('item1-1-2') =====> return 3


How to get specific object's depth with JavaScript?



Not use of id string. like ('item1-2').split('-').length Because each object has randomic id. Is there a simple way?







javascript






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 8 at 9:13







Juntae

















asked Mar 8 at 8:15









JuntaeJuntae

1,56842764




1,56842764












  • Hi! Please take the tour (you get a badge!) and read through the help center, in particular How do I ask a good question? Your best bet here is to do your research, search for related topics on SO, and give it a go. (You'll probably want to use recursion.) If you get stuck and can't get unstuck after doing more research and searching, post a Minimal, Complete, and Verifiable example of your attempt and say specifically where you're stuck. People will be glad to help.

    – T.J. Crowder
    Mar 8 at 8:19












  • Possible duplicate of How to check the depth of an object?

    – Souritra Das Gupta
    Mar 8 at 8:22











  • @SouritraDasGupta It's different. That question is about maximum depth and this is about specific depth.

    – Juntae
    Mar 8 at 9:31

















  • Hi! Please take the tour (you get a badge!) and read through the help center, in particular How do I ask a good question? Your best bet here is to do your research, search for related topics on SO, and give it a go. (You'll probably want to use recursion.) If you get stuck and can't get unstuck after doing more research and searching, post a Minimal, Complete, and Verifiable example of your attempt and say specifically where you're stuck. People will be glad to help.

    – T.J. Crowder
    Mar 8 at 8:19












  • Possible duplicate of How to check the depth of an object?

    – Souritra Das Gupta
    Mar 8 at 8:22











  • @SouritraDasGupta It's different. That question is about maximum depth and this is about specific depth.

    – Juntae
    Mar 8 at 9:31
















Hi! Please take the tour (you get a badge!) and read through the help center, in particular How do I ask a good question? Your best bet here is to do your research, search for related topics on SO, and give it a go. (You'll probably want to use recursion.) If you get stuck and can't get unstuck after doing more research and searching, post a Minimal, Complete, and Verifiable example of your attempt and say specifically where you're stuck. People will be glad to help.

– T.J. Crowder
Mar 8 at 8:19






Hi! Please take the tour (you get a badge!) and read through the help center, in particular How do I ask a good question? Your best bet here is to do your research, search for related topics on SO, and give it a go. (You'll probably want to use recursion.) If you get stuck and can't get unstuck after doing more research and searching, post a Minimal, Complete, and Verifiable example of your attempt and say specifically where you're stuck. People will be glad to help.

– T.J. Crowder
Mar 8 at 8:19














Possible duplicate of How to check the depth of an object?

– Souritra Das Gupta
Mar 8 at 8:22





Possible duplicate of How to check the depth of an object?

– Souritra Das Gupta
Mar 8 at 8:22













@SouritraDasGupta It's different. That question is about maximum depth and this is about specific depth.

– Juntae
Mar 8 at 9:31





@SouritraDasGupta It's different. That question is about maximum depth and this is about specific depth.

– Juntae
Mar 8 at 9:31












2 Answers
2






active

oldest

votes


















3














You need to iterate all objects and if found, take one for each level for the recursion depth.






function getLevelOfId(object, id) 
var level;
if (object.id === id) return 1;
object.children && object.children.some(o => level = getLevelOfId(o, id));
return level && level + 1;


const item = id: 'item1', children: [ id: 'item1-1', children: [ id: 'item1-1-1' , id: 'item1-1-2' , id: 'item1-1-3' ] , id: 'item1-2', children: [ id: 'item1-2-1' ] ] ;

console.log(getLevelOfId(item, 'item1')); // 1
console.log(getLevelOfId(item, 'item1-2')); // 2
console.log(getLevelOfId(item, 'item1-1-1')); // 3
console.log(getLevelOfId(item, 'item1-1-2')); // 3
console.log(getLevelOfId(item, 'foo')); // undefined








share|improve this answer






























    1














    if the structure id & children is fixed, how about search the whole value like "item1-1-1" in the json string:



    "id":"item1","children":["id":"item1-1","children":["id":"item1-1-1","id":"item1-1-2","id":"item1-1-3"],"id":"item1-2","children":["id":"item1-2-1"]]



    level = (number of "") - (number of "") // before the searched positon of the string






    share|improve this answer

























    • The case of item item1-1-1 and item item1-1-2, these two has same level. Perhaps the result of both will be different.

      – Juntae
      Mar 8 at 9:29











    • if the structure is fixed, the results are the same, as indicated, the number of "}" is considered too, so item1-1-1 = 3 - 0, item1-1-2 = 4 - 1

      – nieben
      Mar 8 at 10:04











    • Oh, I didn't know that. That makes sense! I will try this way too!

      – Juntae
      Mar 8 at 10:22











    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',
    autoActivateHeartbeat: false,
    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%2f55059134%2fget-specific-key-depth-in-object-with-key-value%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    3














    You need to iterate all objects and if found, take one for each level for the recursion depth.






    function getLevelOfId(object, id) 
    var level;
    if (object.id === id) return 1;
    object.children && object.children.some(o => level = getLevelOfId(o, id));
    return level && level + 1;


    const item = id: 'item1', children: [ id: 'item1-1', children: [ id: 'item1-1-1' , id: 'item1-1-2' , id: 'item1-1-3' ] , id: 'item1-2', children: [ id: 'item1-2-1' ] ] ;

    console.log(getLevelOfId(item, 'item1')); // 1
    console.log(getLevelOfId(item, 'item1-2')); // 2
    console.log(getLevelOfId(item, 'item1-1-1')); // 3
    console.log(getLevelOfId(item, 'item1-1-2')); // 3
    console.log(getLevelOfId(item, 'foo')); // undefined








    share|improve this answer



























      3














      You need to iterate all objects and if found, take one for each level for the recursion depth.






      function getLevelOfId(object, id) 
      var level;
      if (object.id === id) return 1;
      object.children && object.children.some(o => level = getLevelOfId(o, id));
      return level && level + 1;


      const item = id: 'item1', children: [ id: 'item1-1', children: [ id: 'item1-1-1' , id: 'item1-1-2' , id: 'item1-1-3' ] , id: 'item1-2', children: [ id: 'item1-2-1' ] ] ;

      console.log(getLevelOfId(item, 'item1')); // 1
      console.log(getLevelOfId(item, 'item1-2')); // 2
      console.log(getLevelOfId(item, 'item1-1-1')); // 3
      console.log(getLevelOfId(item, 'item1-1-2')); // 3
      console.log(getLevelOfId(item, 'foo')); // undefined








      share|improve this answer

























        3












        3








        3







        You need to iterate all objects and if found, take one for each level for the recursion depth.






        function getLevelOfId(object, id) 
        var level;
        if (object.id === id) return 1;
        object.children && object.children.some(o => level = getLevelOfId(o, id));
        return level && level + 1;


        const item = id: 'item1', children: [ id: 'item1-1', children: [ id: 'item1-1-1' , id: 'item1-1-2' , id: 'item1-1-3' ] , id: 'item1-2', children: [ id: 'item1-2-1' ] ] ;

        console.log(getLevelOfId(item, 'item1')); // 1
        console.log(getLevelOfId(item, 'item1-2')); // 2
        console.log(getLevelOfId(item, 'item1-1-1')); // 3
        console.log(getLevelOfId(item, 'item1-1-2')); // 3
        console.log(getLevelOfId(item, 'foo')); // undefined








        share|improve this answer













        You need to iterate all objects and if found, take one for each level for the recursion depth.






        function getLevelOfId(object, id) 
        var level;
        if (object.id === id) return 1;
        object.children && object.children.some(o => level = getLevelOfId(o, id));
        return level && level + 1;


        const item = id: 'item1', children: [ id: 'item1-1', children: [ id: 'item1-1-1' , id: 'item1-1-2' , id: 'item1-1-3' ] , id: 'item1-2', children: [ id: 'item1-2-1' ] ] ;

        console.log(getLevelOfId(item, 'item1')); // 1
        console.log(getLevelOfId(item, 'item1-2')); // 2
        console.log(getLevelOfId(item, 'item1-1-1')); // 3
        console.log(getLevelOfId(item, 'item1-1-2')); // 3
        console.log(getLevelOfId(item, 'foo')); // undefined








        function getLevelOfId(object, id) 
        var level;
        if (object.id === id) return 1;
        object.children && object.children.some(o => level = getLevelOfId(o, id));
        return level && level + 1;


        const item = id: 'item1', children: [ id: 'item1-1', children: [ id: 'item1-1-1' , id: 'item1-1-2' , id: 'item1-1-3' ] , id: 'item1-2', children: [ id: 'item1-2-1' ] ] ;

        console.log(getLevelOfId(item, 'item1')); // 1
        console.log(getLevelOfId(item, 'item1-2')); // 2
        console.log(getLevelOfId(item, 'item1-1-1')); // 3
        console.log(getLevelOfId(item, 'item1-1-2')); // 3
        console.log(getLevelOfId(item, 'foo')); // undefined





        function getLevelOfId(object, id) 
        var level;
        if (object.id === id) return 1;
        object.children && object.children.some(o => level = getLevelOfId(o, id));
        return level && level + 1;


        const item = id: 'item1', children: [ id: 'item1-1', children: [ id: 'item1-1-1' , id: 'item1-1-2' , id: 'item1-1-3' ] , id: 'item1-2', children: [ id: 'item1-2-1' ] ] ;

        console.log(getLevelOfId(item, 'item1')); // 1
        console.log(getLevelOfId(item, 'item1-2')); // 2
        console.log(getLevelOfId(item, 'item1-1-1')); // 3
        console.log(getLevelOfId(item, 'item1-1-2')); // 3
        console.log(getLevelOfId(item, 'foo')); // undefined






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 8 at 8:35









        Nina ScholzNina Scholz

        197k15109179




        197k15109179























            1














            if the structure id & children is fixed, how about search the whole value like "item1-1-1" in the json string:



            "id":"item1","children":["id":"item1-1","children":["id":"item1-1-1","id":"item1-1-2","id":"item1-1-3"],"id":"item1-2","children":["id":"item1-2-1"]]



            level = (number of "") - (number of "") // before the searched positon of the string






            share|improve this answer

























            • The case of item item1-1-1 and item item1-1-2, these two has same level. Perhaps the result of both will be different.

              – Juntae
              Mar 8 at 9:29











            • if the structure is fixed, the results are the same, as indicated, the number of "}" is considered too, so item1-1-1 = 3 - 0, item1-1-2 = 4 - 1

              – nieben
              Mar 8 at 10:04











            • Oh, I didn't know that. That makes sense! I will try this way too!

              – Juntae
              Mar 8 at 10:22















            1














            if the structure id & children is fixed, how about search the whole value like "item1-1-1" in the json string:



            "id":"item1","children":["id":"item1-1","children":["id":"item1-1-1","id":"item1-1-2","id":"item1-1-3"],"id":"item1-2","children":["id":"item1-2-1"]]



            level = (number of "") - (number of "") // before the searched positon of the string






            share|improve this answer

























            • The case of item item1-1-1 and item item1-1-2, these two has same level. Perhaps the result of both will be different.

              – Juntae
              Mar 8 at 9:29











            • if the structure is fixed, the results are the same, as indicated, the number of "}" is considered too, so item1-1-1 = 3 - 0, item1-1-2 = 4 - 1

              – nieben
              Mar 8 at 10:04











            • Oh, I didn't know that. That makes sense! I will try this way too!

              – Juntae
              Mar 8 at 10:22













            1












            1








            1







            if the structure id & children is fixed, how about search the whole value like "item1-1-1" in the json string:



            "id":"item1","children":["id":"item1-1","children":["id":"item1-1-1","id":"item1-1-2","id":"item1-1-3"],"id":"item1-2","children":["id":"item1-2-1"]]



            level = (number of "") - (number of "") // before the searched positon of the string






            share|improve this answer















            if the structure id & children is fixed, how about search the whole value like "item1-1-1" in the json string:



            "id":"item1","children":["id":"item1-1","children":["id":"item1-1-1","id":"item1-1-2","id":"item1-1-3"],"id":"item1-2","children":["id":"item1-2-1"]]



            level = (number of "") - (number of "") // before the searched positon of the string







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Mar 8 at 8:57

























            answered Mar 8 at 8:52









            niebennieben

            445




            445












            • The case of item item1-1-1 and item item1-1-2, these two has same level. Perhaps the result of both will be different.

              – Juntae
              Mar 8 at 9:29











            • if the structure is fixed, the results are the same, as indicated, the number of "}" is considered too, so item1-1-1 = 3 - 0, item1-1-2 = 4 - 1

              – nieben
              Mar 8 at 10:04











            • Oh, I didn't know that. That makes sense! I will try this way too!

              – Juntae
              Mar 8 at 10:22

















            • The case of item item1-1-1 and item item1-1-2, these two has same level. Perhaps the result of both will be different.

              – Juntae
              Mar 8 at 9:29











            • if the structure is fixed, the results are the same, as indicated, the number of "}" is considered too, so item1-1-1 = 3 - 0, item1-1-2 = 4 - 1

              – nieben
              Mar 8 at 10:04











            • Oh, I didn't know that. That makes sense! I will try this way too!

              – Juntae
              Mar 8 at 10:22
















            The case of item item1-1-1 and item item1-1-2, these two has same level. Perhaps the result of both will be different.

            – Juntae
            Mar 8 at 9:29





            The case of item item1-1-1 and item item1-1-2, these two has same level. Perhaps the result of both will be different.

            – Juntae
            Mar 8 at 9:29













            if the structure is fixed, the results are the same, as indicated, the number of "}" is considered too, so item1-1-1 = 3 - 0, item1-1-2 = 4 - 1

            – nieben
            Mar 8 at 10:04





            if the structure is fixed, the results are the same, as indicated, the number of "}" is considered too, so item1-1-1 = 3 - 0, item1-1-2 = 4 - 1

            – nieben
            Mar 8 at 10:04













            Oh, I didn't know that. That makes sense! I will try this way too!

            – Juntae
            Mar 8 at 10:22





            Oh, I didn't know that. That makes sense! I will try this way too!

            – Juntae
            Mar 8 at 10:22

















            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.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55059134%2fget-specific-key-depth-in-object-with-key-value%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

            Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

            Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

            Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved