DEV Community

Cover image for # Day 2 | How to resolve it?
Weijuer
Weijuer

Posted on

# Day 2 | How to resolve it?

The problem

let deps = [
    {id: 1, name: 'dep1', pid: 0},
    {id: 2, name: 'dep2', pid: 1},
    {id: 3, name: 'dep3', pid: 1},
    {id: 4, name: 'dep4', pid: 3},
    {id: 5, name: 'dep5', pid: 4},
];

let res = formatDeps(deps);
Enter fullscreen mode Exit fullscreen mode

and the res should be:

[
    {
        "id": 1,
        "name": "dep1",
        "pid": 0,
        "children": [
            {
                "id": 2,
                "name": "dep2",
                "pid": 1,
                "children": []
            },
            {
                "id": 3,
                "name": "dep3",
                "pid": 1,
                "children": [
                    // etc,,,
                ]
            }
        ]
    }
]
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
weijuer profile image
Weijuer

And for now, I find a slim code to resolve it?

function nest(arr, pid) {
 return arr.filter(item => item.pid === pid).map(item => ({...item, children: nest(arr, item.id)}))
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
tsxoxo profile image
Tom Szwaja

Have you tried reduce?

Collapse
 
weijuer profile image
Weijuer

yep, but to code?