对子对象-父结构中的JS对象重新排序 [英] Reorder a JS object in a child-parent structure

查看:57
本文介绍了对子对象-父结构中的JS对象重新排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正面临着断脑的危险(对我而言): 我得到一个带有一个深度为数组的数据对象的json文件,如下所示:

I'm facing a brain-breaker (at leats for me) : I get a json file with a one depth array of data objects like this:

[
{"id":1, "name":"Sport", "parent_id":0, "children":[]},
{"id":2, "name":"Tennis", "parent_id":4, "children":[]},
{"id":3, "name":"Climbing", "parent_id":5, "children":[]},
{"id":4, "name":"Indoor", "parent_id":1, "children":[]},
{"id":5, "name":"Outdoor", "parent_id":1, "children":[]},
{"id":6, "name":"Bowling", "parent_id":4, "children":[]}
]

如何将其转换为树形结构,将子级放置在其父级的子级数组中?对象并非总是按正确的顺序排列,因此子对象可以在数组中的父对象之前出现. (例如我的示例中的ID 2和ID 3)

how can I convert this in a tree-structure where children are put inside their parent's children array? objects are not always in te right order, a child can come before its parent in the array. (like id 2 and 3 in my example)

这是我最终需要它的方式:

This is how I need it in the end:

[
{"id":1, "name":"Sport", "parent_id":0, "children":
  [
    {"id":4, "name":"Indoor", "parent_id":1, "children":
    [
      {"id":2, "name":"Tennis", "parent_id":4, "children":[]},
      {"id":6, "name":"Bowling", "parent_id":4, "children":[]},
    ]},
    {"id":5, "name":"Outdoor", "parent_id":1, "children":
    [
      {"id":3, "name":"Climbing", "parent_id":5, "children":[]}
    ]},
  ]}
]

有什么想法要实现吗?

我尝试遍历元素并在其父级children数组内推入,但是当父级移动后,下一个同级兄弟不再可以找到父级...

I tried iterating over the elements and pushing the inside their parents children array, but when a parent has been moved, the next sibling can't find the parent anymore...

推荐答案

我不确定为什么每个人都如此热衷于编写低效的O 2 算法(嵌套循环),但这是O(n log n)时间中的一个:

I'm not sure why everyone is so keen on writing inefficient O2 algorithms (nested for-loops), but here is one in O(n log n) time:

function treeify(nodes) {
    var indexed_nodes = {}, tree_roots = [];
    for (var i = 0; i < nodes.length; i += 1) {
        indexed_nodes[nodes[i].id] = nodes[i];
    }
    for (var i = 0; i < nodes.length; i += 1) {
        var parent_id = nodes[i].parent_id;
        if (parent_id === 0) {
            tree_roots.push(nodes[i]);
        } else {
            indexed_nodes[parent_id].children.push(nodes[i]);
        }
    }
    return tree_roots;
}

var nodes = [
    {"id":1, "name":"Sport", "parent_id":0, "children":[]},
    {"id":2, "name":"Tennis", "parent_id":4, "children":[]},
    {"id":3, "name":"Climbing", "parent_id":5, "children":[]},
    {"id":4, "name":"Indoor", "parent_id":1, "children":[]},
    {"id":5, "name":"Outdoor", "parent_id":1, "children":[]},
    {"id":6, "name":"Bowling", "parent_id":4, "children":[]}
];

console.log(JSON.stringify(treeify(nodes), undefined, "\t"));

这篇关于对子对象-父结构中的JS对象重新排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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