一维数组和多维数组的转换
一维数组和多维数组的转换
一维数组转多维数组
// idsysarea 表示父级元素
const arr = [
{
id: 110000, // 省市县id,
idsysarea: 100000, // 上级id
mergername: "北京",
name: "北京", // 省市县名称"
},
{
id: 110100,
idsysarea: 110000,
mergername: "北京,北京市",
name: "北京市",
},
{
id: 110101,
idsysarea: 110100,
mergername: "北京,北京市,东城区",
name: "东城区",
},
{
id: 110102,
idsysarea: 110100,
mergername: "北京,北京市,西城区",
name: "西城区",
},
{
id: 110105,
idsysarea: 110100,
mergername: "北京,北京市,朝阳区",
name: "朝阳区",
},
{
id: 120000,
idsysarea: 100000,
mergername: "天津",
name: "天津",
},
{
id: 120100,
idsysarea: 120000,
mergername: "天津,天津市",
name: "天津市",
},
{
id: 120101,
idsysarea: 120100,
mergername: "天津,天津市,和平区",
name: "和平区",
},
{
id: 120102,
idsysarea: 120100,
mergername: "天津,天津市,河东区",
name: "河东区",
},
{
id: 120103,
idsysarea: 120100,
mergername: "天津,天津市,河西区",
name: "河西区",
},
];
function arrToTree(data) {
const result = [];
const obj = {};
// 第一次类似浅拷贝赋值 两次浅拷贝导致data和obj相互影响
data.forEach(item => {
obj[item.id] = item;
});
data.forEach(item => {
// 这儿需要注意item的父级是obj[item.idsysarea]
// 第二次类似浅拷贝赋值
const parent = obj[item.idsysarea];
if (!parent) {
// 找出父级
result.push(obj[item.id]); // 直接item也可以
return;
}
// 表示这个项存在父级
// 即使原来的父级还没创建,由于浅拷贝data和obj上的数据还是会受到影响
(parent.children || (parent.children = [])).push(item);
});
return result;
}
console.log(arrToTree(arr));
多维数组转一维
const arr = [
{
id: 110000,
idsysarea: 100000,
mergername: "北京",
name: "北京",
children: [
{
id: 110100,
idsysarea: 110000,
mergername: "北京,北京市",
name: "北京市",
children: [
{
children: [],
id: 110101,
idsysarea: 110100,
mergername: "北京,北京市,东城区",
name: "东城区",
},
{
children: [],
id: 110102,
idsysarea: 110100,
mergername: "北京,北京市,西城区",
name: "西城区",
},
{
children: [],
id: 110105,
idsysarea: 110100,
mergername: "北京,北京市,朝阳区",
name: "朝阳区",
},
],
},
],
},
{
id: 120000,
idsysarea: 100000,
mergername: "天津",
name: "天津",
children: [
{
id: 120100,
idsysarea: 120000,
mergername: "天津,天津市",
name: "天津市",
children: [
{
children: [],
id: 120101,
idsysarea: 120100,
mergername: "天津,天津市,和平区",
name: "和平区",
},
{
children: [],
id: 120102,
idsysarea: 120100,
mergername: "天津,天津市,河东区",
name: "河东区",
},
{
children: [],
id: 120103,
idsysarea: 120100,
mergername: "天津,天津市,河西区",
name: "河西区",
},
],
},
],
},
];
function deepArr(data) {
if (!Array.isArray(data)) {
return data;
}
const newArr = [];
data.forEach(item => {
if (!item.children) {
return newArr.push(item);
}
const obj = JSON.parse(JSON.stringify(item));
delete obj.children;
newArr.push(obj);
newArr.push(...deepArr(item.children));
});
return newArr;
}
console.log(deepArr(arr));
-
方法 2
function changeArr(data) { let result = []; function getChildrens(item) { let arr = []; if (item.children && item.children.length) { arr = arr.concat(item.children); item.children.forEach(el => { arr = arr.concat(getChildrens(el)); }); } return arr; } data.forEach(item => { result.push(item); result = result.concat(getChildrens(item)); }); return result; } console.log(changeArr(arr));