如何在JavaScript中匹配嵌套对象属性后更新对应值?
解决嵌套对象中custom_fields数组的更新问题
需求
在以下嵌套对象的custom_fields数组中,找到name属性值为Comments的元素,更新其value属性:
{ "id": "476ky1", "custom_id": null, "name": "Reunião com o novo Gerente de Vendas - Airton", "text_content": null, "description": null, "status": { "id": "p3203621_11svBhbO" }, "archived": false, "creator": { "id": 3184709 }, "time_spent": 0, "custom_fields": [{ "id": "36c0de9a-9243-4259-ba57-bd590ba07fe0", "name": "Comments", "value": "dsdsdsds" }], "attachments": [] }
尝试过的无效代码
const updatedComment = [{ name: "Comments", value: "The comment is updated"}]; updateNestedObj(taskData, updatedComment) function updateNestedObj(obj, updates) { const updateToApply = updates.find(upd => upd.id === obj.id); if (updateToApply) { obj.title = updateToApply.content; obj.note = updateToApply.note; } // Apply updates to any child objects for(let k in obj) { if (typeof(obj[k]) === 'object') { updateNestedObj(obj[k], updates); } } }
问题分析
这段代码无法生效的原因:
- 匹配逻辑错误:用
upd.id === obj.id查找更新项,但更新项没有id属性,且目标字段是通过name而非id匹配 - 更新属性错误:代码中试图更新
obj.title和obj.note,但实际需要修改的是value属性 - 未针对数组做处理:
custom_fields是数组,原函数遍历对象时没有遍历数组元素进行匹配
解决方案
方案1:直接定位更新(最简洁)
如果只需要更新特定的Comments字段,直接找到对应元素修改即可:
// 找到custom_fields中name为Comments的元素 const commentField = taskData.custom_fields.find(field => field.name === 'Comments'); // 找到后更新value if (commentField) { commentField.value = "The comment is updated"; }
方案2:通用更新函数(支持多个字段更新)
如果需要批量更新多个custom_fields字段,或者处理嵌套对象中其他位置的custom_fields,可以使用以下函数:
const updatedComment = [{ name: "Comments", value: "The comment is updated"}]; function updateCustomFields(obj, updates) { // 处理当前对象的custom_fields数组 if (Array.isArray(obj.custom_fields)) { obj.custom_fields.forEach(field => { const matchedUpdate = updates.find(update => update.name === field.name); if (matchedUpdate && matchedUpdate.value !== undefined) { field.value = matchedUpdate.value; } }); } // 递归处理嵌套的子对象 for (const key in obj) { if (typeof obj[key] === 'object' && obj[key] !== null) { updateCustomFields(obj[key], updates); } } } // 执行更新 updateCustomFields(taskData, updatedComment);
内容的提问来源于stack exchange,提问作者onit
相关产品推荐
相关产品推荐

