如何动态处理嵌套JSON数组,避免显式指定字段(JIRA场景)
解决方案
核心是从传入的path参数中提取最后一段作为目标赋值键,替代硬编码的'text'。因为调用函数时传入的路径最后一部分就是要赋值的键(比如description.content.content.text的最后一段是text),所以可以通过parts[parts.length - 1]动态获取这个键。
修改后的关键代码
将原代码中硬编码'text'的部分替换为:
const targetKey = parts[parts.length - 1]; Object.keys(newItem).forEach(k => newItem[k] = (k === targetKey) ? value : newItem[k]);
完整修改后的函数
function assignNestedValue(obj, path, value) { const parts = path.split('.'); let current = obj; // 提前获取目标键 const targetKey = parts[parts.length - 1]; for (let i = 0; i < parts.length; i++) { const part = parts[i]; // Handle array dynamically without explicit "type" or "text" if (Array.isArray(current[part])) { if (i === parts.length - 2) { const lastItem = current[part][current[part].length - 1]; // If last item has any empty string, assign value to that key const emptyKey = Object.keys(lastItem).find(k => lastItem[k] === ""); if (emptyKey) { lastItem[emptyKey] = value; } else { // If no empty field, clone the structure dynamically and assign value const newItem = { ...lastItem }; // Copy existing structure Object.keys(newItem).forEach(k => newItem[k] = (k === targetKey) ? value : newItem[k]); current[part].push(newItem); // Push the new item } return; } current = current[part][current[part].length - 1]; // Move to the last item in the array } else if (typeof current[part] === 'undefined') { // Create the path if it doesn't exist current[part] = {}; current = current[part]; } else if (i === parts.length - 1) { current[part] = value; // Assign value to the last part } else { current = current[part]; } } }
效果验证
修改后运行原示例代码,输出和之前完全一致。后续如果新增其他结构(比如description.content.content.anotherKey),只要调用时传入对应的路径(assignNestedValue(..., "description.content.content.anotherKey", "xxx")),函数会自动识别目标键,无需修改函数逻辑,彻底解决维护问题。
内容的提问来源于stack exchange,提问作者Tamizh Selvan k
相关产品推荐
相关产品推荐

