js 数据转换问题
题目
将下面的数据结构
[
{
"id": "1",
"pid": "",
"title": "标题1"
},
{
"id": "2",
"pid": "1",
"title": "标题2"
},
{
"id": "3",
"pid": "1",
"title": "标题3"
},
{
"id": "4",
"pid":"2",
"title": "标题4"
}
]
转换为
[
{
"id": "1",
"pid": "",
"title": "标题1",
"childNode": [
{
"id": "2",
"pid": "1",
"title": "标题2",
"childNode": [
{
"id": "4",
"pid": "2",
"title": "标题4",
"childNode": []
}
]
},
{
"id": "3",
"pid": "1",
"title": "标题3",
"childNode": []
}
]
}
]
实现
递归
const data = `
[
{
"id": "1",
"pid": "",
"title": "标题1"
},
{
"id": "2",
"pid": "1",
"title": "标题2"
},
{
"id": "3",
"pid": "1",
"title": "标题3"
},
{
"id": "4",
"pid":"2",
"title": "标题4"
}
]
`;
// 递归
let jsonArr2 = JSON.parse(data)
console.log('jsonArr1 ------->', jsonArr2)
function add(rootId = "") {
const childNode = jsonArr2.filter(item => item.pid == rootId)
for (let index = 0; index < childNode.length; index++) {
const element = childNode[index];
// 查找该节点下是否还有其他节点
element.childNode = add(element.id)
}
return childNode
}
var obj1 = add()
console.log('jsonArr2-------->', JSON.stringify(obj1))
返回
[{"id":"1","pid":"","title":"标题1","childNode":[{"id":"2","pid":"1","title":"标题2","childNode":[{"id":"4","pid":"2","title":"标题4","childNode":[]}]},{"id":"3","pid":"1","title":"标题3","childNode":[]}]}]
格式化一下
[{
"id": "1",
"pid": "",
"title": "标题1",
"childNode": [{
"id": "2",
"pid": "1",
"title": "标题2",
"childNode": [{
"id": "4",
"pid": "2",
"title": "标题4",
"childNode": []
}]
}, {
"id": "3",
"pid": "1",
"title": "标题3",
"childNode": []
}]
}]
Map 实现
const data2 = `
[
{
"id": "1",
"pid": "",
"title": "标题1"
},
{
"id": "2",
"pid": "1",
"title": "标题2"
},
{
"id": "3",
"pid": "1",
"title": "标题3"
},
{
"id": "4",
"pid":"2",
"title": "标题4"
}
]
`;
let jsonArr2 = JSON.parse(data2)
console.log('jsonArr1 ------->', jsonArr2)
function arrayToTree(data) {
// 最终返回的数据
const rootNodes = [];
// 元素映射map
const itemMap = {};
// 首先,将每个元素添加到项映射中
data.forEach(item => {
itemMap[item.id] = { ...item, children: [] };
});
// 然后,将子节点添加到其父节点的“children”数组中
data.forEach(item => {
//判断是否有 父节点
if (item.pid) {
// 如果存在,直接访问push 到 itemMap 的 children里
itemMap[item.pid].children.push(itemMap[item.id]);
} else {
// 不存在 则 说明 他的上一级就是根节点
// 则将 itemMap 当前节点的id push到最终要返回的map里
rootNodes.push(itemMap[item.id]);
}
});
return rootNodes;
}
var obj2 = arrayToTree(jsonArr2)
console.log('jsonArr2 ------->',JSON.stringify(obj2))
返回
[{"id":"1","pid":"","title":"标题1","children":[{"id":"2","pid":"1","title":"标题2","children":[{"id":"4","pid":"2","title":"标题4","children":[]}]},{"id":"3","pid":"1","title":"标题3","children":[]}]}]
格式化一下
[{
"id": "1",
"pid": "",
"title": "标题1",
"children": [{
"id": "2",
"pid": "1",
"title": "标题2",
"children": [{
"id": "4",
"pid": "2",
"title": "标题4",
"children": []
}]
}, {
"id": "3",
"pid": "1",
"title": "标题3",
"children": []
}]
}]