2 回答
TA贡献2016条经验 获得超9个赞
实现了,主要考了3点:
逻辑
递归
Object.keys()
代码未优化,先去吃饭了,本地测试完成
var data = [
{ id: "2", value: "xxx" },
{ id: "3", value: "xxx" },
{ id: "4", value: "xxx" },
{ id: "6", value: "xxx" },
{ id: "5", value: "xxx" },
{ id: "1", value: "xxx" },
];
var tree = {
"1": {
"children": {
"2": {
"children": {
"4": {
"children": {
"6": {
}
}
}
}
}
}
},
"3": {
"children": {
"5": {
}
}
}
};
function trans(data) {
let dataSort = data.sort((a, b) => {
return a.id - b.id < 0 ? -1 : 1;
});
let tree;
for (let i = 0; i < dataSort.length; i++) {
let idNum = dataSort[i].id;
let isEven = Number(idNum) % 2 === 0;
if (tree === undefined) {
tree = {};
tree[1] = {};
} else if (isEven) {
appendChildAttr(tree[1], idNum);
} else {
if (tree[3] === undefined) {
tree[3] = {};
}else {
appendChildAttr(tree[3], idNum);
}
}
function appendChildAttr(parNode, childrenId) {
if (Object.keys(parNode).length === 0) {
parNode.children = {};
parNode.children[childrenId] = {};
} else {
appendChildAttr(parNode.children[Object.keys(parNode.children)[0]], childrenId);
}
}
}
return tree;
}
console.log(JSON.stringify(trans(data))===JSON.stringify(tree));
添加回答
举报