UNPKG

t-comm

Version:

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

42 lines (35 loc) 1.38 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _typeof = require('@babel/runtime/helpers/typeof'); var validate_isIndex = require('../validate/is-index.js'); function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } var _typeof__default = /*#__PURE__*/_interopDefaultLegacy(_typeof); /** * 设置对象深层属性的值(类似 Lodash 的 _.set) * @param obj 目标对象 * @param path 属性路径(字符串或数组,如 'a.b.c' 或 ['a', 'b', 'c']) * @param value 要设置的值 * @returns 修改后的对象 */ function setWithString(obj, path, value) { if (typeof path === 'string') { // 将字符串路径转换为数组(处理 'a[0].b' 这类格式) path = path.replace(/\[(\d+)\]/g, '.$1').split('.'); } var current = obj; for (var i = 0; i < path.length; i++) { var key = path[i]; if (i === path.length - 1) { // 到达路径末端,直接赋值 current[key] = value; } else { // 确保中间路径存在(不存在则创建空对象/数组) if (!current[key] || _typeof__default["default"](current[key]) !== 'object') { current[key] = validate_isIndex.isIndex(path[i + 1]) ? [] : {}; } current = current[key]; } } return obj; } exports.setWithString = setWithString;