Skip to content

Instantly share code, notes, and snippets.

@xuanvan229
Last active October 10, 2023 04:33
Show Gist options
  • Save xuanvan229/88d03c71b4ea6d17b831c88cb2e8f49c to your computer and use it in GitHub Desktop.
Save xuanvan229/88d03c71b4ea6d17b831c88cb2e8f49c to your computer and use it in GitHub Desktop.
Flat Object
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