现在有arr1
和arr2
两个数组,以arr1
字段顺序
和值
为准,对arr2
进行排序
和更新
value值
let arr1 = [
{
title:"姓名",
property:"name",
width:120
},
{
title:"年龄",
property:"age",
width:120
},
{
title:"角色",
property:"role",
width:120
},
{
title:"修改前",
property:"modify",
width:120
children:[
{
title:"体重",
property:"weight",
width:120
},
{
title:"身高",
property:"tall",
width:120
}
]
}
]
let arr2 = [
{
title:"年龄",
property:"age",
width:100,
date:()=>{},
visible:false,
id:2
},
{
title:"修改前",
property:"modify",
width:100,
children:[
{
title:"身高",
property:"tall",
width:100,
visible:true,
id:5
},
{
title:"体重",
property:"weight",
width:100,
visible:true,
id:6
}
]
},
{
title:"姓名",
property:"name",
width:100,
visible:false,
id:3
},
{
title:"角色",
property:"role",
width:100,
visible:true,
id:1
}
]
想要如下效果
let arr3 = [
{
title:"姓名",
property:"name",
width:120,
visible:false,
id:3
},
{
title:"年龄",
property:"age",
width:120,
visible:false,
id:2,
renderWidth: 140,
date:()=>{}
},
{
title:"角色",
property:"role",
width:120,
visible:true,
id:1
},
{
title:"修改前",
property:"modify",
width:120,
children:[
{
title:"体重",
property:"weight",
width:120,
visible:true,
id:6
},
{
title:"身高",
property:"tall",
width:120,
visible:true,
id:5
}
]
}
]
###这是我试验后的结果
const childOrderMap = new Map();
// 获取到顺序以及 children 的顺序
function getOrder (arr, key) {
return arr.map(item => {
if (item.children) {
childOrderMap.set(item[key], getOrder(item.children, key));
}
return item[key];
});
};
const order = getOrder(arr1, 'property');
function mapOrder(array, order, key) {
return array.sort((a, b) => {
const itemA = a[key];
const itemB = b[key];
// 对 children 进行排序
if (a.children) {
const childOrder = childOrderMap.get(itemA);
a.children = mapOrder(a.children, childOrder, key);
}
if (b.children) {
const childOrder = childOrderMap.get(itemB);
b.children = mapOrder(b.children, childOrder, key);
}
return order.indexOf(itemA) - order.indexOf(itemB);
})
}
const result = mapOrder(arr2, order, 'property');
console.log(result);