Extract all json key from unknown json structure [duplicate]

牧云@^-^@ 提交于 2019-12-12 03:38:07

问题


I'm a problem with an algorithm, I want know all key(nested object, array of object) from some json (unknown structures) file in one array.

{
  "key": "value to array",
  "key": [{
    "key": {
     "key": "value"
     "key": ["value", "value", "value", {"key":"value"}]
    }
  }]
}

The structure can change.

Function(object) {
  var array_of_all_key = []
  return array_of_all_key
}

function allKeys(object) {
  Object.keys(object).reduce((keys, key) => {

 if(typeof object[key] == 'object') {
   allKeys(object[key])
 }

 if(tags[key founded on json]) {
   // my global var
   tags[key] = tags[key] + 1
 }

  });
}

回答1:


Use Object.keys

var obj = {
  key1: 'foo',
  key2: 'bar'
};
var keys = Object.keys(obj);
//keys === ['key1', 'key2'];



回答2:


Just use Object.keys and recursive functions.

function allKeys(object) {
  return Object.keys(object).reduce((keys, key) => 
    keys.concat(key, 
      typeof object[key] === 'object' ? allKeys(object[key]) : []
    ), 
    []
  );
}


来源:https://stackoverflow.com/questions/38000115/extract-all-json-key-from-unknown-json-structure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!