We have the following kind of object:
const obj = {
a: { "=": 0 },
b: {
c: { "=": 1 },
d: {
e: { "=": 2 },
f: {
g: { "=": 3 }
}
}
}
}
I am trying to write a function that returns an array with the object keys, including the nested ones, but groups them if they are nested and their values is not { "=": "something" }
. To better explain I'll write a sample output desired for the object above:
["a", "b.c", "b.d.e", "b.d.f.g"]
All I have achieved for now is a function that only traverses the first level, but I admit I got stuck on the recursive part where the same function will apply on every level of the object until it reaches an entry of type { "=": "something" }
. Follows my actual code:
function nestedObject(obj) {
const operator = "="
const attributes = []
void (function traverse(obj) {
if (isObject(obj)) { // <-- isObject(obj) just checks if typeof obj == "object", !Array.isArray(obj), obj !== null
for (const [k,v] of Object.entries(obj)) {
let attr = k
for (const [k_,v_] of Object.entries(v)) {
if (operator !== k_) {
attr += "." + k_
// here is where the recursive part should start
// but I didn't figure out yet how to make it right.
// Of course calling traverse(v_) doesn't give the desired result.
}
attributes.push(attr)
}
}
}
})(obj)
console.log(attributes) // <-- will output ["a", "b.c", "b.d"]
}
I hope I did explain well enough. I don't even know if this is possible, but I think it is. Would love to hear some ideas.