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

JS使用reduceRight处理jsoneditor路径时数组被转对象,如何修正逻辑?

解决方案

方案1:直接更新完整JSON对象(最适合表单提交场景)

你需要的是完整的提交结构,直接基于原始JSON的深拷贝做路径定位修改即可,逻辑最简单且不会出错:

// 原始JSON对象
const originalJson = {
  "array": [80, 50]
};
// jsoneditor返回的修改节点
const node = {
  path: ["array", 1],
  value: 60
};

// 1. 深拷贝原始数据,避免污染原对象
const submittedJson = structuredClone(originalJson);
// 2. 遍历路径定位到父节点
let current = submittedJson;
for (let i = 0; i < node.path.length - 1; i++) {
  current = current[node.path[i]];
}
// 3. 给最后一级路径赋值,自动兼容数组下标和对象属性
const lastKey = node.path.at(-1);
current[lastKey] = node.value;

// 输出结果:{ array: [80, 60] }
console.log(submittedJson);

该方案天然支持任意多层嵌套的对象/数组混合结构,比如路径为["user", "addressList", 0, "city"]也可以正常处理。

方案2:生成带完整数组的delta对象

如果确实需要单独生成delta而非修改全量对象,可以在reduceRight的遍历中增加原始节点类型判断:

// 工具函数:根据路径从原始对象获取对应节点
function getNodeByPath(obj, path) {
  return path.reduce((curr, key) => curr?.[key], obj);
}

const delta = node.path.reduceRight((childVal, currKey, index) => {
  // 取当前路径段对应的父节点路径
  const parentPath = node.path.slice(0, index);
  const parentNode = getNodeByPath(originalJson, parentPath);
  // 父节点为数组时,拷贝原数组后修改对应下标
  if (Array.isArray(parentNode)) {
    const newArr = [...parentNode];
    newArr[currKey] = childVal;
    return newArr;
  }
  // 父节点为对象时正常生成键值对
  return { [currKey]: childVal };
}, node.value);

// 输出结果:{ array: [80, 60] }
console.log(delta);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 03:54:05