2 回答

TA貢獻(xiàn)2016條經(jīng)驗(yàn) 獲得超9個(gè)贊
實(shí)現(xiàn)了,主要考了3點(diǎn):
邏輯
遞歸
Object.keys()
代碼未優(yōu)化,先去吃飯了,本地測(cè)試完成
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));
添加回答
舉報(bào)