简体   繁体   中英

Convert flat array to nested parent-child format

Currently, I have an array with below format:

[{
    key: "a"
}, {
    key: "b"
}, {
    key: "c"
}, {
    key: "d"
}, {
    key: "e"
}]

Every element in the array is the parent of element next to it.

Required to convert it to below format:

[{
    key: "a",
    Nodes: [{
        key: "b",
        Nodes: [{
            key: "c",
            Nodes: [{
                key: "d",
                Nodes: [{
                    key: "e"
                }]
            }]
        }]
    }]
}]

I have achieved this, but the logic I have implemented is quite lengthy and now I want to optimize code.

So I want to know the most optimized way to do this

Using Array#reduceRight makes this simple:

 const array = [{ key: "a" }, { key: "b" }, { key: "c" }, { key: "d" }, { key: "e" }]; const nested = array.reduceRight((Nodes, obj) => { if (Nodes) { return [Object.assign({}, obj, { Nodes })]; } else { return [obj]; } }, null); console.log(nested); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM