I have the following object:
var abc = {
1: "Raggruppamento a 1",
2: "Raggruppamento a 2",
3: "Raggruppamento a 3",
4: "Raggruppamento a 4",
count: '3',
counter: {
count: '3',
},
5: {
test: "Raggruppamento a 1",
tester: {
name: "Georgi"
}
}
};
I would like to retrieve the following result:
is that possible using nodejs maybe with the help of plugins?
You can do this by recursively traversing the object:
function getDeepKeys(obj) {
var keys = [];
for(var key in obj) {
keys.push(key);
if(typeof obj[key] === "object") {
var subkeys = getDeepKeys(obj[key]);
keys = keys.concat(subkeys.map(function(subkey) {
return key + "." + subkey;
}));
}
}
return keys;
}
Running getDeepKeys(abc)
on the object in your question will return the following array:
["1", "2", "3", "4", "5", "5.test", "5.tester", "5.tester.name", "count", "counter", "counter.count"]
Smaller version, no side effect, just 1 line in function body:
function objectDeepKeys(obj){
return Object.keys(obj).filter(key => obj[key] instanceof Object).map(key => objectDeepKeys(obj[key]).map(k => `${key}.${k}`)).reduce((x, y) => x.concat(y), Object.keys(obj))
}
var abc = {
1: "Raggruppamento a 1",
2: "Raggruppamento a 2",
3: "Raggruppamento a 3",
4: "Raggruppamento a 4",
count: '3',
counter: {
count: '3',
},
5: {
test: "Raggruppamento a 1",
tester: {
name: "Ross"
}
}
};
function objectDeepKeys(obj){
return Object.keys(obj)
.filter(key => obj[key] instanceof Object)
.map(key => objectDeepKeys(obj[key]).map(k => `${key}.${k}`))
.reduce((x, y) => x.concat(y), Object.keys(obj))
}
console.log(objectDeepKeys(abc))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With