如何在嵌套对象中添加级别

时间:2018-02-17 23:17:41

标签: javascript jquery arrays

我正在尝试在动态嵌套对象中添加级别。例如

[{
    "_id": "5a8855df9a8bb60e749c9d87",
    "name": "Test3",
    "children": []
  },
  {
    "_id": "5a8856569a8bb60e749c9d88",
    "name": "Test4",
    "children": [{
      "_id": "5a885f6cf12a351f5465d2ad",
      "name": "Subtest4",
      "children": [{
        "_id": "5a88ab0d11650a1a0c0454ea",
        "name": "Sub45",
        "children": []
      }]
    }]
  },
]

我想在这个嵌套对象中添加级别,如下所示:

{
  "_id": "5a8856569a8bb60e749c9d88",
  "name": "Test4",
  level: 1,
  "children": [{
    "_id": "5a885f6cf12a351f5465d2ad",
    "name": "Subtest4",
    level: 2 "children": [{
      "_id": "5a88ab0d11650a1a0c0454ea",
      "name": "Sub45",
      level: 3 "children": []
    }]
  }]
},

这是动态创建的列表,我想根据其级别添加“ - ”。如果等级为1,则仅添加1' - '

预期输出

Test3
Test4
-Subtest4
--Sub45

这就是我正在做的事情

function tree(list,level) {

    _.each(list,e => {
        $('#parent').append(`<option value='${e._id}'>${e.name}</option>`)
        if(e.children.length) tree(e.children,++level);
    });        
}

1 个答案:

答案 0 :(得分:0)

这是错误的++level,因为您在同一级别添加+1,更改为level + 1

此方法使用$.each中的jQuery来循环数组。

&#13;
&#13;
var array = [{    "_id": "5a8855df9a8bb60e749c9d87",    "name": "Test3",    "children": []  },  {    "_id": "5a8856569a8bb60e749c9d88",    "name": "Test4",    "children": [{      "_id": "5a885f6cf12a351f5465d2ad",      "name": "Subtest4",      "children": [{        "_id": "5a88ab0d11650a1a0c0454ea",        "name": "Sub45",        "children": []      }]    }]  },];

function tree(list, level, dashes) {
  $.each(list, function() {
    $('#parent').append(`<option value='${this.id}'>${dashes}${this.name}</option>`)    
    if (this.children.length) tree(this.children, level + 1, `${dashes}-`);
  });
}

tree(array, 1, '');
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='parent'>
</select>
&#13;
&#13;
&#13;