【问题标题】:How to create nested group of properties [duplicate]如何创建嵌套的属性组[重复]
【发布时间】:2017-11-06 13:48:29
【问题描述】:

我正在尝试创建我的 javascript 原始对象的嵌套组。

item=[
{name:'Root1',id:1,parentId:null},
{name:'Root2',id:2,parentId:null},
{name:'Root3',id:4,parentId:null},
{name:'Root1.1',id:4,parentId:1},
{name:'Root1.1.1',id:5,parentId:4},
{name:'Root4',id:6,parentId:null}
];

这是我的原始数据,

我希望这些数据采用如下格式

var modified=
[
    {
        title:Root1,
        id:1,
        chields:
        {
            title:'Root 1.1',
            id:4,
            clields:
            {
                title:'Root 1.1.1',
                id:5,
                chield:
                {
                    title:'New',
                    id:null
                }
            }
        }
    }
];

【问题讨论】:

  • 你试过搜索吗?我确定我已经回答并在 SO 上看到了很好的答案

标签: javascript arrays object


【解决方案1】:

我得到了我的解决方案here

 var children = _.filter( array, function(child){ return child.parentid == parent.id; });

    if( !_.isEmpty( children )  ){
        if( parent.id == 0 ){
           tree = children;   
        }else{
           parent['children'] = children
        }
        _.each( children, function( child ){ unflatten( array, child ) } );                    
    }

    return tree;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多