赞
踩
let array = [ { id: 1, name: "小明", children: [ { id: 2, name: "小红", }, ], }, { id: 3, name: "小刚", children: [] }, ]; function getFlatArr(arr) { return arr.reduce((a, item) => { let flatArr = [...a, item]; if (item.children) { flatArr = [...flatArr, ...getFlatArr(item.children)]; } return flatArr; }, []); } console.log(getFlatArr(array)); function getNameByIdFromArr(arr, id) { return getFlatArr(arr).find((item) => item.id === id).name; } console.log(getNameByIdFromArr(array, 2)); // 结果: '小红' // 根据id:[1,2,3]筛选出对应的label值的方法(data是getFlatArr新的数组,value是选中的id数组) filterbrandLabel (data, value) { const labelAll = [] if (Array.isArray(value)) { for (const item of value) { for (const v of data) { if (String(item) === String(v.value)) { labelAll.push(v.label) } } } } else { for (const v of data) { if (String(value) === String(v.value)) { labelAll.push(v.label) } } } return labelAll.length > 0 ? labelAll.join('、') : '无' }, getbrandNameByIdFromArr () { const newarry = this.getFlatArr(array) return this.filterbrandLabel(newarry, [1,2,3]) }, console.log(getbrandNameByIdFromArr()); // 最终结果: ['小明','小红','小刚']
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。