嵌套对象中指定键值对替换:薪酬费率编辑应用开发求助
解决方案
核心思路是通过递归遍历嵌套对象,精准匹配最深层包含type和value字段的目标节点,直接完成值替换,避免冗余的层级判断逻辑。
实现代码
/** * 递归更新嵌套对象中目标节点的value * @param {object} obj 要修改的原始嵌套对象 * @param {Array} updatePath 要更新的字段路径,示例:['Physicians', 'telehealth', 'weekdayEncounters'] * @param {number} newValue 替换的新value值 * @returns {object} 更新后的新对象(避免直接修改原对象导致的副作用) */ function updateRateValue(obj, updatePath, newValue) { // 深拷贝原对象,避免修改原数据 const newObj = JSON.parse(JSON.stringify(obj)); let current = newObj; // 遍历到目标节点的父级 for (let i = 0; i < updatePath.length - 1; i++) { const key = updatePath[i]; if (!current[key]) return newObj; // 路径不存在直接返回原对象 current = current[key]; } const targetKey = updatePath[updatePath.length - 1]; // 确认是目标节点才更新 if (current[targetKey] && typeof current[targetKey] === 'object' && 'value' in current[targetKey]) { current[targetKey].value = newValue; } return newObj; }
调用示例
比如要把「医师类远程问诊工作日接诊费率」从15改成20,调用方式如下:
// 原始费率数据 const rateData = { Physicians: { telehealth: { orgName: "ORG B", weekdayEncounters: { type: "each", value: 15 }, weeknightEncounters: { type: "each", value: 16.25 }, weekendDayEncounters: { type: "each", value: 16.25 }, weekendNightEncounters: { type: "each", value: 17.25 }, holidayEncounters: { type: "each", value: 17.25 }, stipend: { type: "lump", value: 0 }, }, }, NonPhysicians: { telehealth: { orgName: "ORG B", weekdayEncounters: { type: "each", value: 15 }, weeknightEncounters: { type: "each", value: 16.25 }, weekendDayEncounters: { type: "each", value: 16.25 }, weekendNightEncounters: { type: "each", value: 17.25 }, holidayEncounters: { type: "each", value: 17.25 }, stipend: { type: "lump", value: 0 }, }, }, date: "07-2021", orgName: "ORG B", ltc: false, }; const updatedData = updateRateValue(rateData, ['Physicians', 'telehealth', 'weekdayEncounters'], 20);
优化建议
- 如果你需要批量更新所有匹配条件的节点,而非指定路径的单个节点,可以把路径遍历逻辑换成全递归遍历,只要遇到包含
value属性的对象就执行更新 - 深拷贝如果担心性能问题,可以换成浅拷贝逐层处理,简单场景下JSON序列化深拷贝足够用
- 用户编辑时可以把当前编辑字段的路径和输入的新值绑定,触发保存时直接调用上面的方法即可,不需要单独为每个字段写更新逻辑
内容的提问来源于stack exchange,提问作者CourtneyJ
相关产品推荐
相关产品推荐

