问题
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