You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中如何按指定路径修改JSON中重复出现的特定key的值

解决方案

方案1:使用第三方npm包实现

直接使用lodash的set方法即可,该方法专门用于按指定路径修改对象属性,天然支持嵌套对象、数组场景,只会修改匹配路径的字段,不会改动其他位置的同名key。
你可以按需单独安装lodash.set包,无需引入整个lodash库:

npm install lodash.set

使用示例:

const set = require('lodash.set');
// 注意路径需要和实际JSON结构匹配:
// 你提供的JSON中transactions是顶层数组,currency在数组元素的amount子字段下
// 因此修改第一个transaction的amount.currency的正确路径如下
const targetPath = "transactions.0.amount.currency";
const newValue = "EUR";

set(SampleJSON, targetPath, newValue);

修改后SampleJSON.transactions[0].amount.currency会变成EUR,itemlist.items下的同名currency字段不会被改动。

方案2:手动实现轻量赋值函数

如果不想引入第三方依赖,可以自己实现按路径赋值的方法,代码如下:

function setValueByPath(obj, path, value) {
    // 兼容a.b.c和a[0].b两种路径写法
    const keyList = path.replace(/\[(\d+)\]/g, '.$1').split('.');
    let currentNode = obj;
    for (let i = 0; i < keyList.length; i++) {
        const currentKey = keyList[i];
        // 遍历到最后一级直接赋值
        if (i === keyList.length - 1) {
            currentNode[currentKey] = value;
            return true;
        }
        // 中间节点不存在则自动初始化
        if (!currentNode[currentKey]) {
            // 下一级是数字则初始化为数组,否则初始化为对象
            currentNode[currentKey] = /^\d+$/.test(keyList[i+1]) ? [] : {};
        }
        currentNode = currentNode[currentKey];
    }
    return false;
}

// 使用示例
setValueByPath(SampleJSON, "transactions.0.amount.currency", "EUR");

注意事项

你给出的示例路径product.transactions.currency和提供的JSON结构不匹配:

  • 你提供的JSON中顶层product字段是字符串类型,值为delivery,没有子字段transactions
  • transactions是顶层数组,且currency字段在transactions数组元素的amount子字段下
    修正路径为transactions.0.amount.currency即可匹配到你需要修改的目标字段。
    如果需要修改transactions数组下所有元素的amount.currency,遍历数组拼接路径后调用赋值方法即可。

内容的提问来源于stack exchange,提问作者ArrchanaMohan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 01:30:01