JavaScript格式将对象数组放入嵌套的子级 [英] JavaScript format array of objects into nested children

查看:41
本文介绍了JavaScript格式将对象数组放入嵌套的子级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有parentId的对象数组,并对要放入嵌套的"children"并适当排序的数组的排序值进行排序.

I have an array of objects with parentId and sort values that I'd like to put into an array with nested 'children' and sorted appropriately.

例如,以下是数据:

[{
    id: 1,
    sort: 2,
    parentId: null,
    name: 'A'
}, {
    id: 2,
    sort: 1,
    parentId: 1,
    name: 'A.1'
}, {
    id: 3
    sort: 2,
    parentId: 1,
    name: 'A.2'
}, {
    id: 4,
    sort: 1,
    parentId: null,
    name: 'B'
}]

我要转换的方式如下:

[{
    id: 4,
    sort: 1,
    parentId: null,
    name: 'B',
    children: []
}, {
    id: 1,
    sort: 2,
    parentId: null,
    name: 'A',
    children: [{
        id: 2,
        sort: 1,
        parentId: 1,
        name: 'A.1'
    }, {
        id: 3
        sort: 2,
        parentId: 1,
        name: 'A.2'
    }]
}]

对此进行了排序(id为4的顶部,因为sort为1),并且子级被嵌套并且也进行了相应的排序.

This is sorted (id 4 being at the top, since sort is 1) and the children are nested and also sorted accordingly.

有什么好的方法建议吗?我可以递归地遍历以应用子级,但是不确定如何保持排序.

Any suggestions on a good way to do this? I can recursively loop through to apply children, but not sure how I can maintain sorting on this.

推荐答案

这是一个建议,该建议首先进行排序,然后进行过滤.

This is a proposal which sorts first and filters after that.

排序采用属性 parentId sort .这对于下一步是必要的,因为过滤"需要排序的数组.

The sorting takes the properties parentId and sort. This is necessary for the next step, because the "filtering" needs a sorted array.

稍后使用 Array#filter() ,这是 thisArgs ,用于引用节点以可能插入子项.

Later the array is filterd with Array#filter(), Here is thisArgs used for referencing nodes for a possible insertation of children.

更新未排序的( id / parentId )数据.

Update for unsorted (id/parentId) data.

var array = [{ id: 1, sort: 2, parentId: null, name: 'A' }, { id: 2, sort: 1, parentId: 1, name: 'A.1' }, { id: 3, sort: 2, parentId: 1, name: 'A.2' }, { id: 4, sort: 1, parentId: null, name: 'B' }],
    nested;

array.sort(function (a, b) {
    return (a.parentId || -1) - (b.parentId || -1) || a.sort - b.sort;
});

nested = array.filter(function (a) {
    a.children = this[a.id] && this[a.id].children;
    this[a.id] = a;
    if (a.parentId === null) {
        return true;
    }
    this[a.parentId] = this[a.parentId] || {};
    this[a.parentId].children = this[a.parentId].children || [];
    this[a.parentId].children.push(a);
}, Object.create(null));

document.write('<pre>' + JSON.stringify(nested, 0, 4) + '</pre>');

这篇关于JavaScript格式将对象数组放入嵌套的子级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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