Request you to please help in building a function in javascript to obtain the mentioned output from the input given.
INPUT : An object (possibly a nested object)
example :
{
"message":"string" ,
"data1": {
"Output1": {
"leaf1": "abc",
"Leaf2": "123"
}
}
"data2": {
"Output2": {
"leaf3": "abc",
"leaf4": "123"
}
}
}
OUTPUT : An array of string
Example : str= ["message", "data1.Output1.leaf1", "data1.Output1.leaf2" , "data2.Output2.leaf3","data2.Output2.leaf4"]
CodePudding user response:
Something like this it will work
const getBranches = (data, prefix=[]) => {
if (typeof(data) !== 'object') {
return prefix.join('.')
}
return Object.entries(data).flatMap(([k, v]) => getBranches(v, [...prefix, k]))
}
const data = {
"message": "string",
"data1": {
"Output1": {
"leaf1": "abc",
"Leaf2": "123"
}
},
"data2": {
"Output2": {
"leaf3": "abc",
"leaf4": "123"
}
}
}
console.log(getBranches(data))