Last active
October 10, 2023 04:33
-
-
Save xuanvan229/88d03c71b4ea6d17b831c88cb2e8f49c to your computer and use it in GitHub Desktop.
Flat Object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const dataSource = { | |
one: { | |
two: 3, | |
four: [5, 6, 7], | |
}, | |
eight: { | |
nine: { | |
ten: 11, | |
eleven: [ | |
{ | |
twelve: 13, | |
}, | |
], | |
}, | |
}, | |
}; | |
function main(obj, parentKey = "") { | |
let result = {}; | |
for (const key in obj) { | |
const value = obj[key]; | |
const newKey = parentKey ? `${parentKey}/${key}` : key; | |
if ( | |
Array.isArray(value) && | |
value.length > 0 && | |
typeof value[0] === "object" | |
) { | |
for (let i = 0; i < value.length; i++) { | |
const arrayKey = `${newKey}/${i}`; | |
Object.assign(result, main(value[i], arrayKey)); | |
} | |
} else if (typeof value === "object") { | |
Object.assign(result, main(value, newKey)); | |
} else { | |
result[newKey] = value; | |
} | |
} | |
return result; | |
} | |
console.log(main(dataSource)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment