Heim > Fragen und Antworten > Hauptteil
Jetzt haben wir die folgende Datenstruktur:
[{
id: 1,
pid: 0,
name: "年级"
}, {
id: 2,
pid: 1,
name: "一年级"
}, {
id: 3,
pid: 1,
name: "二年级"
}, {
id: 4,
pid: 0,
name: "专业"
}, {
id: 5,
pid: 4,
name: "单片机开发"
}]
Schreiben Sie eine JS-Methode, um sie in die folgenden Formatdaten zu konvertieren:
[{
id: 1,
pid: 0,
name: "年级",
children: [{
id: 2,
pid: 1,
name: "一年级"
}, {
id: 3,
pid: 1,
name: "二年级"
}]
}, {
id: 4,
pid: 0,
name: "专业",
children: [{
id: 5,
pid: 4,
name: "单片机开发"
}]
}]
PHP中文网2017-06-28 09:29:56
var list = [{
id: 1,
pid: 0,
name: "年级"
}, {
id: 2,
pid: 1,
name: "一年级"
}, {
id: 3,
pid: 1,
name: "二年级"
}, {
id: 4,
pid: 0,
name: "专业"
}, {
id: 5,
pid: 4,
name: "单片机开发"
}];
function parseList (list) {
var map = {};
list.forEach(function (item) {
if (!map[item.id]) {
map[item.id] = item;
}
});
list.forEach(function (item) {
if (item.pid != 0) {
map[item.pid].chidren ? map[item.pid].chidren.push(item) : map[item.pid].chidren = [item];
}
});
return list.filter(function (item) {
return item.pid === 0;
});
}
var newList = parseList(list);
学习ing2017-06-28 09:29:56
var list = [
{ id: 1, pid: 0, name: "年级" },
{ id: 2, pid: 1, name: "一年级" },
{ id: 3, pid: 1, name: "二年级" },
{ id: 4, pid: 0, name: "专业" },
{ id: 5, pid: 4, name: "单片机开发" }
];
// 生成查找表,可以按 id 查到节点
const dict = list.reduce((all, item) => {
all[item.id] = item;
return all;
}, {});
// 由于原始数据没有 id 为 0 的根节点,
// 这里模拟一个,最终它的 children 就是实际的所有根节点
var root = {
id: 0
};
dict[0] = root;
// 循环添加关系
list.forEach(item => {
const parent = dict[item.pid];
// 确保父节点的 children 存在
parent.children = parent.children || [];
parent.children.push(item);
});
// 输出结果 root.children
// 注意,root 不是结果,root.children 才是
console.log(JSON.stringify(root.children, null, 4));
某草草2017-06-28 09:29:56
参考一下
var sortedData = data.reduce((result, item) => {
result[item.id] = Object.assign({}, item)
return result
}, [])
var result = sortedData.reduce((result, item) => {
if (item.pid === 0) {
result.push(item)
} else {
if (sortedData[item.pid].children) {
sortedData[item.pid].children.push(item)
} else {
sortedData[item.pid].children = [item]
}
}
return result
}, [])