0

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
 }

  });
}

2 Answers2

0

Use Object.keys

var obj = {
  key1: 'foo',
  key2: 'bar'
};
var keys = Object.keys(obj);
//keys === ['key1', 'key2'];
zzzzBov
  • 174,988
  • 54
  • 320
  • 367
0

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]) : []
    ), 
    []
  );
}
Louay Alakkad
  • 7,132
  • 2
  • 22
  • 45