getValueByReference
根据对象的引用获取值
参数
参数名 | 参数类型 | 参数说明 |
---|---|---|
target | T extends Record<string, any> | 要设置值的对象 |
refer | string |string[] | 对象的引用路径 |
源代码&使用
ts
import { getValueByReference } from '@manzhixing/utilsxy';
const obj = {
userInfo: {
name: "chengbotao",
},
};
getValueByReference(obj, "userInfo.name"); // "chengbotao"
// getValueByReference(obj, ["userInfo", "name"]); // "chengbotao"
ts
/*
* @Author: Chengbotao
* @Contact: https://github.com/chengbotao
*/
export function getValueByReference<T extends Record<string, any>>(
target: T,
refer: string | string[]
): any {
const refers: string[] =
typeof refer === 'string' ? (refer as string).split('.') : (refer as string[]);
return refers.reduce((obj, key) => {
return obj && obj[key];
}, target);
}