I'm trying to get all the keys in an object, in a recursive way:
let keys = [];
const getAllKeys = (object) => {
//Supposedly, `keys` should be here.
Object.keys(object).some((k) => {
if (object[k] && typeof object[k] === "object") {
keys.push(k);
getAllKeys(object[k]);
}
});
return keys;
};
const obj = {
key1: {
key2: {
key3: {}
}
}
};
getAllKeys(obj);
console.log(keys);
And as you can see, it works, but the problem is that keys is outside this function, but I need it to be inside so that I can just import this function and use it. I tried wrapping it in another, inner function, but it doesn't work.
What can I do here?