1.今天遇到个让我头疼的需求,就是把后端返回过来的数组backendArr的item的name属性进行拼接,具体需求的描述请看下面的代码
// 后端返回的数据
let backendArr = [{
fatherIndex: -1,
locationName: '主楼',
locationType: 1,
},{
fatherIndex: -1,
locationName: '副楼',
locationType: 1,
},{
fatherIndex: 0,
locationName: '二层',
locationType: 21,
},{
fatherIndex: 1,
locationName: '三层',
locationType: 21,
},{
fatherIndex: 2,
locationName: '201',
locationType: 32,
},{
fatherIndex: 3,
locationName: '301',
locationType: 32,
}]
// 前端渲染所需要的数组格式
targetArr = [{
locationName: "主楼;二层;201",
locationType: 32,
},{
locationName: "副楼;三层;301",
locationType: 32,
}]
// locationType取拼接的最后一项数据的locationType
/*
已知后端数组backendArr,里面每个item都有一个fatherIndex,它的意思就是该item的父级item在backendArr里的索引值。
举例:locationName为'201'的item,其fatherIndex为2,此数组里index为2的item是'二层',说明'201'的父级item是'二层';
然后看'二层'item,其fatherIndex为0,说明'二层'的父级item是'主楼';
然后继续看'主楼'item,其fatherIndex为-1,说明是最高级item,无需再向上查找。
我们要做的就是把'201'、'二层'和'主楼'三个(实际情况有可能不止三层)的locationName拼接起来,以";"分隔,即:locationName: "主楼;二层;201",
*/
2.举例:locationName为"201"的item,其fatherIndex为2,此数组里index为2的item是"二层",说明"201"的父级item是"二层";
然后看"二层"item,其fatherIndex为0,说明"二层"的父级item是"主楼";
然后继续看"主楼"item,其fatherIndex为-1,说明是最高级item,无需再向上查找。我们要做的就是把"201"、"二层"和"主楼"三个(实际情况有可能不止三层)的locationName拼接起来,以";"分隔,即:locationName: "主楼;二层;201";
(什么?你问我为什么按索引值来搞,这样一把数组重新排列岂不是全完蛋?我的评价是这是后端大哥对我的小小考验!)
3.解决思路:其实洒家第一时间想到的是使用递归,但考虑到栈溢出的隐患,还是觉得改成普通循环来实现,毕竟条条大路通罗马!具体解决方法请看下方代码^_^
const backendArr = [
{
fatherIndex: -1,
locationName: '主楼',
locationType: 1,
},
{
fatherIndex: -1,
locationName: '副楼',
locationType: 1,
},
{
fatherIndex: 0,
locationName: '二层',
locationType: 21,
},
{
fatherIndex: 1,
locationName: '三层',
locationType: 21,
},
{
fatherIndex: 2,
locationName: '201',
locationType: 32,
},
{
fatherIndex: 3,
locationName: '301',
locationType: 32,
},
];
// 拼接名称函数
const findLocationName = (locations, index) => {
const path = [];
let current = index;
//关键代码,在此处循环地拼接地点名称,将父级item的index赋值给current,继续拼接,直到current===-1(已查找到最高级地点)为止
while (current !== -1) {
path.push(locations[current].locationName);
current = locations[current].fatherIndex;
}
return path.reverse().join(';');
};
let targetArr = backendArr
// 首先筛选掉fatherIndex为-1的最高级地点
.filter((location) => location.fatherIndex !== -1)
// 然后遍历剩余的每个地点,调用拼接名称函数
.map((location) => ({
locationName: findLocationName(backendArr, location.fatherIndex) + ';' + location.locationName,
locationType: location.locationType,
}));
console.log(targetArr, '拼接成功了')
4.targetArr打印出来的结果出来如下图所示:
5.有人也许会问该结果里的前两项不符合题意,但其实在本人的具体开发中,该数组还有个locationType属性,我可以通过这个属性来筛选(.filter)出自己所需要的数据,通罗马就行嘛:
const finalArr = targetArr.filter(item=>item.locationType === 32)
console.log(finalArr)
6.以上就是本文的全部内容了,希望能够对你有帮助,也欢迎各位在评论区讨论,可以的话就点个赞吧^_^