封装公共方法
/**
* @description: 解决select选中一个option绑定的id,想取出该option中的其他属性值
* 场景:选中值后不但要传id,还要额外传递该选中的option中的其他值给后端,一般用于最后接口传参处理参数使用
* @param {string|number} value 选中的option的id
* @param {Array} options option数组,可能包含嵌套结构
* @param {string} key 需要取出的属性值的key
* @return {string} 返回属性值,若未找到则返回空字符串
* @example:
* const options = [{id: 1, name: '张三', children: [{id: 2, name: '李四'}]}]
* const value = 2
* const key = 'name'
* const result = getOptionValueRecursive(value, options, key)
*/
export function getOptionValueRecursive(
value: string | number,
options: Array<any>,
key: string
): string {
for (const option of options) {
if (option.id === value) {
return option[key];
}
if (option.children && option.children.length > 0) {
const nestedResult = getOptionValueRecursive(value, option.children, key);
if (nestedResult) {
return nestedResult;
}
}
}
return "";
}