I'm attempting to write a function that will loop through a deeply nested object, and create a shallow object by concatenating parent/child keys.
For example, if we have the object:
let original = {
a: {
b: "",
c: {
d: "",
e: ""
},
f: "",
},
g: ""
}
Then I would like the outcome to be this:
let result = {
"a[b]": "",
"a[c][d]": "",
"a[c][e]": "",
"a[f]": "",
"g": ""
}
I've got as far as the code snippet below, but it's not quite correct.
let original = {
a: {
b: "",
c: {
d: "",
e: ""
},
f: "",
},
g: ""
}
function flattenData(obj) {
let result = {};
for (let i in obj) {
if ((typeof obj[i]) === 'object') {
let temp = this.flattenData(obj[i])
for (let j in temp) {
result[`[${i}][${j}]`] = temp[j];
}
} else {
result[i] = obj[i];
}
}
return result;
}
console.log(flattenData(original));