const arr = [{ id: 1, parent: null }, { id: 2, parent: null }, { id: 3, parent: 1 }, { id: 4, parent: 2 }, { id: 5, parent: 3 }, { id: 6, parent: 1 }]; function tree(parent, arr) { for (let j = arr.length - 1; j >= 0; j--) { if (!parent) { parent = []; } if (parent.id) { if (arr[j].parent === parent.id) { if (!parent.children) { parent.children = []; } parent.children.push(tree(arr[j], arr)); } } else { if(!arr[j].parent){ parent.push(tree(arr[j], arr)); } } } return parent; } const res = tree(null, arr); // const res = tree({ // id: null // }, arr); console.log(JSON.stringify(res));