How to get the key value from nested object

前端 未结 5 968
刺人心
刺人心 2020-12-06 15:32

I am having below object where I am trying to get all the id values.

[{
    \"type\": \"test\",
    \"id\": \"100\",
    \"values\": {
        \"name\": \"A         


        
5条回答
  •  半阙折子戏
    2020-12-06 16:03

    To get the keys from nested objects, you first need to put your code in a function, then for each of the top-level keys, check if it's an array or object. If it is, just call your function again from within that function (weird, I know.) Just make sure you don't skip the check of whether it's an object. You'll get stuck in an infinite loop. Something like this:

    function parseObjectKeys(obj) {
      for (var prop in obj) {
        console.log(prop)
        var sub = obj[prop]
        if (typeof(sub) == "object") {
          parseObjectKeys(sub);
        }
      }
    }
    

    Here's a more complex example: https://jsfiddle.net/tfqLnzLm/1/

提交回复
热议问题