简体   繁体   English

将平面数组转换为嵌套的父子格式

[英]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: 使用Array#reduceRight可简化此操作:

 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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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