Skip to content

setValueByReference

根据对象的引用设置值

参数

参数名参数类型参数说明
targetany要设置值的对象
referstring|string[]对象的引用路径
valany要设置的值

源代码&使用

ts
import { setValueByReference } from '@manzhixing/utilsxy';

const obj = {
  a: {
      b: 1,
  },
};

setValueByReference(obj, "a.b", 2);
// setValueByReference(obj, ["a", "b"], 2);
{ a: { b: 2 } }
ts
/*
 * @Author: Chengbotao
 * @Contact: https://github.com/chengbotao
 */
export function setValueByReference(target: any, refer: string | string[], val: any): any {
  const refers: string[] =
    typeof refer === 'string' ? (refer as string).split('.') : (refer as string[]);

  return (
    (refers.slice(0, -1).reduce((obj, key) => {
      return (obj[key] = obj[key] || {});
    }, target)[refers.pop() as string] = val),
    target
  );
}