I have an object similar to the one below:
const obj = {
"test1": {
"test12": "val1",
"test13": {
"test131": "val1",
"test132": "val2"
}
},
"test2": "val2"
}
I want to receive the keys as follows:
const keys = [["test1", "test12", "test13", "test131", "test132"], ["test2"]];
2 Answers 2
You can recursively process the entries in the object, collecting keys as you go and flattening the result arrays at all levels other than the top:
const obj = {
"test1": {
"test12": "val1",
"test13": {
"test131": "val1",
"test132": "val2"
}
},
"test2": null,
"test3": {
"test31": "val3"
},
"test4": {
"test41": [1, 2, 3, 4]
}
}
const getKeys = (obj, flat = false) => {
const keys = Object.entries(obj)
.map(([k, v]) => v instanceof Object && !(v instanceof Array) ? [k, ...getKeys(v, true)] : [k])
return flat ? keys.flat() : keys
}
const allKeys = getKeys(obj)
console.log(allKeys)
answered Sep 14, 2022 at 7:07
Nick
147k23 gold badges67 silver badges106 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Viktor Luft
This code will run into an error if one of the values is "null" and might not work as expected if one of the values would be an array.
Nick
@ViktorLuft thanks for pointing that out. I've corrected the code to ensure it works correctly in those cases
Here you go:
const obj = {
"test1": {
"test12": "val1",
"test13": {
"test131": "val1",
"test132": "val2"
}
},
"test2": "val2"
};
const mapToKeys = ([key, value]) => {
if (Object.prototype.toString.call(value) === '[object Object]') {
return [key, ...getKeys(value)];
}
return [key];
};
const getKeys = (o) => Object.entries(o).flatMap(mapToKeys);
const keys = Object.entries(obj).map(mapToKeys);
console.log(keys);
answered Sep 14, 2022 at 7:04
Viktor Luft
9415 silver badges10 bronze badges
Comments
lang-js
Object.keysshould help here.