Skip to content

Instantly share code, notes, and snippets.

@1242035
Created July 25, 2019 11:31
Show Gist options
  • Save 1242035/066bbf2f0abf001e631fef5684fff6c7 to your computer and use it in GitHub Desktop.
Save 1242035/066bbf2f0abf001e631fef5684fff6c7 to your computer and use it in GitHub Desktop.
rebuild array from tree es6
export function listToFlatArray(treeStructure) {
let flatten = (children, extractChildren, level, parent) => Array.prototype.concat.apply(
children.map(x => ({ ...x, level: level || 1, parent: parent || null })),
children.map(x => flatten(extractChildren(x) || [], extractChildren, (level || 1) + 1, x.id))
);
let extractChildren = x => x.children;
return flatten(extractChildren(treeStructure), extractChildren).map(x => delete x.children && x);
}
/*
ex:
let treeStructure = {
"children": [{
"id": 1,
"title": "home",
"parent": null,
"children": []
}, {
"id": 2,
"title": "about",
"parent": null,
"children": [{
"id": 3,
"title": "team",
"parent": 2,
"children": [{
"id": 5,
"title": "company",
"parent": null,
"children": []
}]
}, {
"id": 4,
"title": "company",
"parent": 2,
"children": []
}]
}]
};
listToFlatArray(treeStructure);
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment