Skip to content

getValueByReference

根据对象的引用获取值

参数

参数名参数类型参数说明
targetT extends Record<string, any>要设置值的对象
referstring|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);
}