今天在CSDN上问答区看到一个提问的小伙伴,是想要将一维数组转化为三位数组的需求,正好不是很忙,乐于助人的我立马给这位同学安排上
下面是后端同学返给我们的一维数组数据格式
[{'品牌': 'xiaomi', '机型': '10', '配置': '512'},{'品牌': 'xiaomi', '机型': '10', '配置': '128'},{'品牌': 'xiaomi', '机型': '11', '配置': '128'},{'品牌': 'xiaomi', '机型': '11', '配置': '64'},{'品牌': 'iPhone', '机型': '10', '配置': '128'},{'品牌': 'iPhone', '机型': '11', '配置': '64'},{'品牌': 'iPhone', '机型': '12', '配置': '64'},{'品牌': 'honor', '机型': '4', '配置': '256'},{'品牌': 'honor', '机型': '5', '配置': '128'},{'品牌': 'honor', '机型': '6', '配置': '128'}];
下面是我们想要转化的数据格式(转化成三维数组 第一层级为品牌、第二层级为型号、第三层级为配置)
[{"value": "xiaomi","label": "xiaomi","children": [{"value": "10","label": "10","children": [{"value": "512","label": "512"},{"value": "128","label": "128"}]},{"value": "11","label": "11","children": [{"value": "128","label": "128"},{"value": "64","label": "64"}]}]},{"value": "iPhone","label": "iPhone","children": [{"value": "10","label": "10","children": [{"value": "128","label": "128"}]},{"value": "11","label": "11","children": [{"value": "64","label": "64"}]},{"value": "12","label": "12","children": [{"value": "64","label": "64"}]}]},{"value": "honor","label": "honor","children": [{"value": "4","label": "4","children": [{"value": "256","label": "256"}]},{"value": "5","label": "5","children": [{"value": "128","label": "128"}]},{"value": "6","label": "6","children": [{"value": "128","label": "128"}]}]}]
首先我们定义一个arr变量接收我们的一维数组,然后将arr作为参数传递给我们转化数组的函数,函数返回的就是我们最终的三维数组了
下面就是我们的arrConversion源码
arrConversion (arr) {let keys = Object.keys(arr[0])let level1 = keys[0]//获取一级属性名称let level2 = keys[1]//获取二级属性名称let level3 = keys[2]//获取三级属性名称let list = Array.from(new Set(arr.map(item => {return item[level1]})))let subList = []list.forEach(res => {arr.forEach(ele => {if (ele[level1] === res) {let nameArr = subList.map(item => item.value)if (nameArr.indexOf(res) !== -1) {let nameArr2 = subList[nameArr.indexOf(res)].children.map(item => item.value)if (nameArr2.indexOf(ele[level2]) !== -1) {subList[nameArr.indexOf(res)].children[nameArr2.indexOf(ele[level2])].children.push({value: ele[level3],label: ele[level3],})} else {subList[nameArr.indexOf(res)].children.push({value: ele[level2],label: ele[level2],children: [{value: ele[level3],label: ele[level3],}]})}} else {subList.push({value: res,label: res,children: [{value: ele[level2],label: ele[level2],children: [{value: ele[level3],label: ele[level3],}]}]})}}})})return subList}
输出结果正确
✨原创不易,希望大家多多支持!!!\textcolor{blue}{原创不易,希望大家多多支持!!!}原创不易,希望大家多多支持!!!
👍 点赞,你的认可是我创作的动力!\textcolor{green}{点赞,你的认可是我创作的动力!}点赞,你的认可是我创作的动力!
⭐️ 收藏,你的青睐是我努力的方向!\textcolor{green}{收藏,你的青睐是我努力的方向!}收藏,你的青睐是我努力的方向!
✏️ 评论,你的意见是我进步的财富!\textcolor{green}{评论,你的意见是我进步的财富!}评论,你的意见是我进步的财富!