【问题标题】:How do I create nested array from flatten array which has corresponding flatten arrays using javascript (underscore.js, lodash.js)如何使用javascript(underscore.js,lodash.js)从具有相应展平数组的展平数组创建嵌套数组
【发布时间】:2015-07-29 16:46:35
【问题描述】:

在以下结构中有一个对象数组

    [
        {id: 1, title: 'hello', parent: 0},
        {id: 2, title: 'hello', parent: 0},
        {id: 3, title: 'hello', parent: 1},
        {id: 4, title: 'hello', parent: 3},
        {id: 5, title: 'hello', parent: 4},
        {id: 6, title: 'hello', parent: 4},
        {id: 7, title: 'hello', parent: 3},
        { id: 8, title: 'hello', parent: 2}
    ]

我想创建一个具有以下结构的新数组

    [
          {id: 1, title: 'hello', parent: 0, children: [
          {id: 3, title: 'hello', parent: 1, children: [
          {id: 4, title: 'hello', parent: 3, children: [
          {id: 5, title: 'hello', parent: 4},
          {id: 6, title: 'hello', parent: 4}
          ]},
          {id: 7, title: 'hello', parent: 3}
          ]}
          ]},
          {id: 2, title: 'hello', parent: 0, children: [
          {id: 8, title: 'hello', parent: 2}
          ]}
    ]

【问题讨论】:

  • 既然您基本上是在谈论如何构建和利用树结构,那么让我指出一个可能相关的问题。 stackoverflow.com/questions/8640823/… 没有像原始问题一样标记为重复并不清楚所需的数据格式是否是硬性要求。

标签: javascript underscore.js


【解决方案1】:

试试这个:

// Original array
var array = [        
    {id: 1, title: 'hello', parent: 0},
    {id: 2, title: 'hello', parent: 0},
    {id: 3, title: 'hello', parent: 1},
    {id: 4, title: 'hello', parent: 3},
    {id: 5, title: 'hello', parent: 4},
    {id: 6, title: 'hello', parent: 4},
    {id: 7, title: 'hello', parent: 3},
    { id: 8, title: 'hello', parent: 2}
];

// Nesting
var obj, ii, o;
for(var i = 0; i < array.length; i++) {
    obj = array[i];
    if(obj.parent > 0) {
        for(var ii = 0; ii < array.length; ii++) {
            o = array[ii];
            if(o.id == obj.parent) {
                if(!o.children) o.children = [];
                o.children.push(obj);
                break;
            }
        }
    }
}


// Cleanup
var tempArray = [];
var obj;
for(var i = 0; i < array.length; i++) {
    obj = array[i];
    if(obj.parent == 0) {
        tempArray.push(obj);
    }
}
array = tempArray;

// Log to check how everything turned out
console.log(array);

http://jsfiddle.net/sxb5fzak/2/

【讨论】:

    猜你喜欢
    • 2013-11-06
    • 2017-12-26
    • 1970-01-01
    • 1970-01-01
    • 2014-05-28
    • 1970-01-01
    • 2016-05-02
    • 2021-10-12
    • 2012-10-31
    相关资源
    最近更新 更多