Skip to content

Instantly share code, notes, and snippets.

@BunHouth
Created May 7, 2020 14:44
Show Gist options
  • Save BunHouth/1163a5fe0a12adbe1a41d67bb1312ff2 to your computer and use it in GitHub Desktop.
Save BunHouth/1163a5fe0a12adbe1a41d67bb1312ff2 to your computer and use it in GitHub Desktop.
const data = [
{id: 1, name: "meat", parent_id: null},
{id: 2, name: "vegi", parent_id: null},
{id: 3, name: "drink", parent_id: null},
{id: 4, name: "fish", parent_id: 1},
{id: 5, name: "beef", parent_id: 1},
{id: 6, name: "pork", parent_id: 1},
{id: 7, name: "raw", parent_id: 2},
{id: 8, name: "boiled", parent_id: 2},
{id: 9, name: "carbonate", parent_id: 3},
{id: 10, name: "fried rice beef", parent_id: 5},
{id: 11, name: "fried rice pork", parent_id: 5},
{id: 12, name: "morning glory", parent_id: 8},
{id: 13, name: "coca", parent_id: 9}
];
const results = {};
const findChilds = id => {
const results = [];
data.map(child => {
if (child.parent_id === id) {
results.push(child);
child.childs = findChilds(child.id);
}
});
return results;
};
const records = data
.filter(object => !object.parent_id)
.map(object => {
object.childs = findChilds(object.id);
return object;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment