1

For example, if i have

{
   "key1":{
      "key2":[
         {
            "key3":[
               {
                  "key4":{
                     "key5":0
                  }
               },
               {
                  "key6":{
                     "key7":""
                  }
               }
            ]
         },
         {
            "key8":{
               "key9":true
            }
         }
      ]
   }
}

is there a way to get all the keys like this?

["key1", "key2", "key3", "key4", "key5", "key6", "key7", "key8", "key9"]

edit: i tried the suggestion here, but it didn't work out Typescript: what could be causing this error? "Element implicitly has an 'any' type because type 'Object' has no index signature"

Community
  • 1
  • 1
icda
  • 87
  • 2
  • 9
  • Yes. Possible duplicate of http://stackoverflow.com/questions/2549320/looping-through-an-object-tree-recursively – hackerrdave Jan 30 '17 at 03:27
  • Possible duplicate of [looping through an object (tree) recursively](http://stackoverflow.com/questions/2549320/looping-through-an-object-tree-recursively) – nicovank Jan 30 '17 at 03:32
  • having some problem with this solution http://stackoverflow.com/questions/41929287/typescript-what-could-be-causing-this-error-element-implicitly-has-an-any-t – icda Jan 30 '17 at 05:17

1 Answers1

0

You need a recursive function in order to iterate.

Try like this

var obj = {
  "key1": {
    "key2": [{
      "key3": [{
        "key4": {
          "key5": 0
        }
      }, {
        "key6": {
          "key7": ""
        }
      }]
    }, {
      "key8": {
        "key9": true
      }
    }]
  }
};
var keys = [];

function collectKey(obj) {
  if (obj instanceof Array) {
    //console.log("array");
    for (var i = 0; i < obj.length; i++) {
      collectObj(obj[i]);
    }
  } else if (typeof obj == "object") {
    //console.log("object");
    collectObj(obj)
  } else {
    return;
  }
}

function collectObj(obj) {
  for (var i = 0; i < Object.keys(obj).length; i++) {
    keys.push(Object.keys(obj)[i]);
    collectKey(obj[Object.keys(obj)[i]]);
  }
}
collectKey(obj);
console.log(keys);
Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80