不多说了,直接贴代码
/**
* @arr-需要遍历的数组或树
* @val-当前的值
* @arrkey-第二个参数的值对应数组中的key
* @arrLabel-第二个参数的值对应数组中需要输出的值
* @Example: valueToLabel([{id: 555, label: "测试"}, {id: 666, label: "测试2"}], 666, 'id', 'label'); => 从数组中找到 id 为 666 对应的 label
*/
export function valueToLabel(arr, val, arrkey, arrLabel){
let hasFound = false, result = null;
let fn = function (arr) {
if (Array.isArray(arr) && !hasFound) {
arr.forEach(item => {
if (item[arrkey] == val) {
result = item[arrLabel];
hasFound = true;
} else if (item.children) {
fn(item.children);
}
})
}
}
fn(arr);
return result;
}