UNPKG

t-comm

Version:

专业、稳定、纯粹的工具库

31 lines (27 loc) 670 B
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); /** * 深度赋值 * @param keyStr 以点拼接的 key,比如 foo.bar * @param target 目标对象 * @param value 目标值 * @example * ```ts * const obj = { a: { b: 1 } }; * deepSet('a.c', obj, 2); * * console.log(obj); * // { a: { b: 1, c: 2 } } * ``` */ function deepSet(keyStr, target, value) { keyStr.split('.').reduce(function (obj, key, index, arr) { if (index === arr.length - 1) { obj[key] = value; // 最终赋值 } else { obj[key] = obj[key] || {}; // 保留原有结构 } return obj[key]; }, target); } exports.deepSet = deepSet;