【发布时间】:2019-12-14 11:01:23
【问题描述】:
我正在从从 HTTP 请求获得的 JSON 数组设置树视图。 数组中的每个对象都有一个链接到父对象的父 ID。我需要从这个数组逻辑中创建一个树视图。
循环应该运行多次,直到父 ID 为 0。它可能有多个级别。
我的 JSON 数组看起来像这样。 (基于console.log(level1['_source']);)
1: {_index: "fud_alvr", _type: "analyse", _id: "31", _score: 1.4142135, _source: {
ID: "66"
content: "Berlin"
indexID: "9"
parentID: "26"
}, …}
2: {_index: "fud_alvr", _type: "analyse", _id: "26", _score: 1.4142135, _source: {
ID: "26"
content: "Germany"
indexID: "9"
parentID: "0"
}, …}
3: {_index: "fud_alvr", _type: "analyse", _id: "272", _score: 1.4142135, _source: {…}, …}
4: {_index: "fud_alvr", _type: "analyse", _id: "392", _score: 1.4142135, _source: {…}, …}
5: {_index: "fud_alvr", _type: "analyse", _id: "33", _score: 1.4142135, _source: {…}, …}
6: {_index: "fud_alvr", _type: "analyse", _id: "64", _score: 1.4142135, _source: {…}, …}
7: {_index: "fud_alvr", _type: "analyse", _id: "27", _score: 1.4142135, _source: {…}, …}
8: {_index: "fud_alvr", _type: "analyse", _id: "65", _score: 1.4142135, _source: {…}, …}
9: {_index: "fud_alvr", _type: "analyse", _id: "438", _score: 1.4142135, _so
应该是这样构建的->
- 德国
- 柏林
- 克罗伊茨贝格
- 慕尼黑
- 法国
- 巴黎
这是我的 POST http 请求。
$http({
method: 'POST',
url: url,
data: body,
timeout: 4000
}).then(function (result) {
$scope.doc = result.data.hits.hits;
$scope.doc.forEach(level1 => {
// TODO in level1['_source'] are all elements. SO what to do next ?
console.log(level1['_source']);
});
}, function (error) {
errorCallback(error);
});
我正在考虑从 0,1,2,3,4,5 开始计算 parentID... 并将每组相同的 id 存储在下一个数组内的新数组中。
如果德国的 ID 为 26 且 parentID = 0,则为第一级。 如果 Berlin、Munich、Hamburg 的 parentID = 26,则它是德国内部的第二层……以此类推。
我不确定这里最好的逻辑是什么。
【问题讨论】:
-
$scope.doc instanceof Array是否评估为true?它看起来像一个对象,在这种情况下它没有forEach方法。 -
为什么要在客户端创建树视图?为什么不在服务器端创建?我认为您将数据保存在数据库中,并且有几种方法可以在数据库引擎上保存和创建树视图数据。
-
我在服务器端没有访问权限。所以唯一的解决方案是循环遍历每个元素并将其排序为树结构。
标签: javascript arrays json angularjs http