【发布时间】:2018-05-25 12:14:20
【问题描述】:
我从一个看起来像这样(非常简化)的表中获取 JSON 数据:
我得到的 JSON 格式如下:
const myObjOriginal = {
"rows": [{
"name": "row 1",
"cells": [{
"name": "level 1",
"id": 1
}, {
"name": "first level 2",
"id": 2
}, {
"name": "endpoint 1",
"id": 4
}]
}, {
"name": "row 2",
"cells": [{
"name": "level 1",
"id": 1
}, {
"name": "first level 2",
"id": 2
}, {
"name": "endpoint 2",
"id": 5
}]
}, {
"name": "row 3",
"cells": [{
"name": "level 1",
"id": 1
}, {
"name": "second level 2",
"id": 3
}, {
"name": "endpoint 3",
"id": 6
}]
}]
};
我需要做的是把它变成树而不是表,输出如下所示:
const goalObject = [{
"name": "level 1",
"id": 2,
"children": [{
"name": "first level 2",
"id": 2,
"children": [{
"name": "endpoint 1",
"id": 4
}, {
"name": "endpoint 2",
"id": 5
}]
}, {
"name": "second level 2",
"id": 3,
"children": [{
"name": "endpoint 3",
"id": 6
}]
}]
}];
我尝试了各种方法,包括 map、reduce、filter、for 循环和 forEach,但都无济于事。
我意识到我需要以某种方式创建一个递归函数,但我也没有让它工作。
这是我尝试过的一件事的示例,但我知道这是完全错误的......
function getChildrenOfCurrentItem(rowIndex = 0, cellIndex = 0) {
let current = {};
let myObj = {};
for(let i = 0; i < myCopy.rows.length; i++){
next = myCopy.rows[i].cells[cellIndex];
const cells = myCopy.rows[i].cells;
const isSame = compareObjects(current, next);
if(!isSame){
current = next;
myObj.item = current;
//cellIndex++;
for(let j = 0; j < cells.length; j++){
let cell = cells[j];
console.log('cell', cell);
}
}
console.log('myObj', myObj);
//cellIndex++;
if(cellIndex < max) {
getChildrenOfCurrentItem(rowIndex, cellIndex);
}
rowIndex++;
}
return myObj;
}
【问题讨论】:
标签: javascript arrays json tree javascript-objects