如何创建嵌套的属性组 [英] How to create nested group of properties

查看:55
本文介绍了如何创建嵌套的属性组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am Trying to create nested group of my javascript raw object.

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}
];

这是我的原始数据,

我想要这种格式的数据,例如波纹管

I want this data in format some like bellow

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
                }
            }
        }
    }
];


推荐答案

我的解决方案此处

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

这篇关于如何创建嵌套的属性组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆