setValueByReference
根据对象的引用设置值
参数
参数名 | 参数类型 | 参数说明 |
---|---|---|
target | any | 要设置值的对象 |
refer | string |string[] | 对象的引用路径 |
val | any | 要设置的值 |
源代码&使用
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
);
}