简体   繁体   English

将json row-items转换为嵌套的javascript对象数组

[英]turn json row-items into nested javascript objects array

Given the following array of json objects: 给定以下json对象数组:

var items = [
    {id:1, parentId:0, name:'item1'},
    {id:2, parentId:1, name:'item1.2'},
    {id:3, parentId:1, name:'item1.3'},
    {id:4, parentId:3, name:'item3.4'},
    {id:5, parentId:3, name:'item3.5'},
    ...more nesting, levels, etc.
];

And a base object like: 和基础对象如:

var myObj = function(id, parentId, name, children){
    this.id = id;
    this.parentId = parentId;
    this.name = name;
    this.children = children;
};

how do I use recursion to loop through this items array and build a new array like so: 如何使用递归循环遍历此items数组并构建一个新数组,如下所示:

var newArray = [
    new myObj(1, 0, 'item1', [
        new myObj(2, 1, 'item1.2', []),
        new myObj(3, 1, 'item1.3', [
            new myObj(4, 3, 'item3.4', []),
            new myObj(5, 3, 'item3.5', [])
        ])
    ]);
];

any help is greatly appreciated 任何帮助是极大的赞赏

edit: the parent/child relationship can be infinite. 编辑:父/子关系可以是无限的。 so i'm looking for a recursion function that would convert the first "items" array into the second "newarray" 所以我正在寻找一个递归函数,将第一个“items”数组转换为第二个“newarray”

The title of your question is a bit misleading. 你的问题的标题有点误导。 You're trying to convert an array of items into a tree-like nested object. 您正在尝试将项目数组转换为树状嵌套对象。

Your use of the Object constructor is a bit redundant. 您对Object构造函数的使用有点多余。 Use quasi-literal notation ( {foo:bar} ) instead. 请改用准文字符号( {foo:bar} )。 Actually, you don't even need to create new objects, you can use the original ones. 实际上,您甚至不需要创建新对象,您可以使用原始对象。

First, convert the list to an object to facilitate referencing by id: 首先,将列表转换为对象以便于通过id引用:

var map = {}
for (var i = 0; i < items.length; i++) {
   map[items[i].id] = items[i];
}

Now, iterate through the items and add children array: 现在,遍历项目并添加子数组:

var newArray = [];
for (id in map) {
    var item = map[id];
    var parent = map[item.parentId];
    if (parent) {
        parent.children = parent.children || [];
        parent.children.push(item); // add reference to item
    } else { // root
        newArray.push(item);
    }
}

Note that this modifies the original items array, and newArray holds pointers to its entries. 请注意,这会修改原始items数组, newArray保存指向其条目的指针。 If you don't want that, create a copy of items first. 如果您不想这样,请先创建items副本

I don't know if this helps, but in this fiddle there's an iterative solution that creates that newArray. 我不知道这是否有帮助,但在这个小提琴中有一个迭代的解决方案,可以创建newArray。
Using a json obj as an array and then adding the children as you iterate over the items array. 使用json obj作为数组,然后在迭代items数组时添加子项。

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

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