引入
ts
import { setWithString, merge } from 't-comm';
// 不支持 tree-shaking 的项目
import { setWithString, merge} from 't-comm/lib/lodash-mini/index';
// 只支持 ESM 的项目
import { setWithString, merge} from 't-comm/es/lodash-mini/index';setWithString(obj, path, value)
描述:设置对象深层属性的值(类似 Lodash 的 _.set)
参数:
| 参数名 | 描述 |
|---|---|
| obj | 目标对象 |
| path | 属性路径(字符串或数组,如 'a.b.c' 或 ['a', 'b', 'c']) |
| value | 要设置的值 |
返回: 修改后的对象
示例
ts
// 字符串路径
setWithString({}, 'a.b.c', 1);
// { a: { b: { c: 1 } } }
// 数组路径
setWithString({}, ['a', 'b', 'c'], 'x');
// { a: { b: { c: 'x' } } }
// 数组下标语法 'a[0].b'
setWithString({}, 'a[0].b', 'y');
// { a: [{ b: 'y' }] }
// 已有对象上覆盖/扩展
setWithString({ a: { b: 1 } }, 'a.c', 2);
// { a: { b: 1, c: 2 } }merge()
描述:Merge objects which will create
参数:
示例
ts
merge({ a: 1 }, { b: 2 }); // { a: 1, b: 2 }
// 深合并
merge({ a: { x: 1 } }, { a: { y: 2 } });
// { a: { x: 1, y: 2 } }
// 后者覆盖前者
merge({ a: 1, b: 2 }, { b: 3 });
// { a: 1, b: 3 }
// 数组:直接覆盖(不会合并)
merge({ a: [1, 2, 3] }, { a: [4] });
// { a: [4] }
// 多源合并
merge({ a: 1 }, { b: 2 }, { c: 3 });
// { a: 1, b: 2, c: 3 }