JavaScript实现扁平数组结构与JSON树形结构相互转换递归reducecontinuepushconcatfor of
Posted web半晨
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaScript实现扁平数组结构与JSON树形结构相互转换递归reducecontinuepushconcatfor of相关的知识,希望对你有一定的参考价值。
目录
1、扁平数组结构转换成JSON树形结构
function convert(list)
let result = [];
const map = list.reduce((pre, cur) =>
pre[cur.id] = cur;
return pre;
, );
for (const item of list)
if (item.parentId === 0)
result.push(item);
continue;
if (item.parentId in map)
let parent = map[item.parentId];
parent.children = parent.children || [];
parent.children.push(item);
return result;
let flatOriginData = [
id: 5, parentId: 2, name: "目录1-1-1", ,
id: 1, parentId: 0, name: "目录1", ,
id: 13, parentId: 9, name: "目录2-2-3", ,
id: 3, parentId: 1, name: "目录1-2", ,
id: 2, parentId: 1, name: "目录1-1", ,
id: 12, parentId: 9, name: "目录2-2-2", ,
id: 4, parentId: 1, name: "目录1-3", ,
id: 7, parentId: 0, name: "目录2", ,
id: 9, parentId: 7, name: "目录2-2", ,
id: 6, parentId: 2, name: "目录1-1-2", ,
id: 11, parentId: 9, name: "目录2-2-1", ,
id: 8, parentId: 7, name: "目录2-1", ,
id: 10, parentId: 7, name: "目录2-3", ,
];
console.log('flatOriginData:', convert(flatOriginData));
// flatOriginData: (2) […, …]
2、JSON树形结构转换成扁平数组结构
function flatten(data)
return data.reduce((pre, cur) =>
const id, name, parentId, children = [] = cur;
return pre.concat([ id, name, parentId ], flatten(children));
, []);
let treeOriginData = [
id: 1, parentId: 0, name: "目录1",
children: [
id: 3, parentId: 1, name: "目录1-2" ,
id: 2, parentId: 1, name: "目录1-1",
children: [
id: 5, parentId: 2, name: "目录1-1-1" ,
id: 6, parentId: 2, name: "目录1-1-2"
]
,
id: 4, parentId: 1, name: "目录1-3"
]
,
id: 7, parentId: 0, name: "目录2",
children: [
id: 9, parentId: 7, name: "目录2-2",
children: [
id: 13, parentId: 9, name: "目录2-2-3" ,
id: 12, parentId: 9, name: "目录2-2-2" ,
id: 11, parentId: 9, name: "目录2-2-1"
]
,
id: 8, parentId: 7, name: "目录2-1" ,
id: 10, parentId: 7, name: "目录2-3"
]
];
console.log('treeOriginData:', flatten(treeOriginData));
// treeOriginData: (13) […, …, …, …, …, …, …, …, …, …, …, …, …]
以上是关于JavaScript实现扁平数组结构与JSON树形结构相互转换递归reducecontinuepushconcatfor of的主要内容,如果未能解决你的问题,请参考以下文章
Javascript中扁平化数据结构与JSON树形结构转换详解
原生JavaScript+HTML5实现树形目录结构一维数组生成多维数组detailssummary