简体   繁体   English

Underscore.js带有子数组的新对象数组

[英]Underscore.js New Array of Objects with child arrays

I have an array of objects in the following structure 我有以下结构的对象数组

var projects = [
    {id:'1',name:'project1', parentid:"null"},
    {id:'2',name:'project2', parentid:"null"},
    {id:'3',name:'subproject1', parentid:"1"},
    {id:'4',name:'subproject2', parentid:"1"},
    {id:'5',name:'subproject3', parentid:"2"}
];

I would like to make a new array with the following structure 我想制作一个具有以下结构的新数组

var newProjects = [
    {text:'project1', children:[
        {id:'3',name:'subproject1', parentid:"1"},
        {id:'4',name:'subproject2', parentid:"1"}
    ]},
    {text:'project2', children:[
        {id:'5',name:'subproject3', parentid:"2"}
    ]}
]

I have been able to do this using a bunch of loops and if statements but would like to clean it up by using Underscore.js but been unable to do so. 我已经能够使用一堆循环和if语句来做到这一点,但想通过使用Underscore.js对其进行清理,但无法做到这一点。 could someone please point me in the right direction? 有人能指出我正确的方向吗?

Based on the data given, you can probably get away with using a simple groupBy and map . 根据给定的数据,您可能可以使用简单的groupBymapgroupBy

Something like this: 像这样:

var grouped = _.groupBy(projects, 'parentid');
var newProjects = _.map(grouped['null'], function (project, id) {
    return {
        text: project.name,
        children: grouped[project.id]
    };
});

If you have deeper nesting, you'll need to work out a more robust solution, but this should give you an idea on what to do. 如果您有更深层的嵌套,则需要制定出更强大的解决方案,但这应该使您对如何做有所了解。

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

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