javascript - 如何更新这样的嵌套状态?

标签 javascript reactjs multidimensional-array

例如,我如何使用 key: 1311 更新对象并返回更新后的状态?假设我不知道它的确切位置......只知道它的键值。

state = {
  iow: [
    {
      key: 1,
      iow_description: "EARTH WORK",
      unit: null,
      rate: null,
      children: [
        {
          key: 11,
          iow_description: "Sub-head",
          unit: null,
          rate: null
        },
        {
          key: 12,
          iow_description: "Sub-head",
          unit: null,
          rate: null,
          children: [
            {
              key: 121,
              iow_description: "Sub-head",
              unit: "cu.m",
              rate: 100.0
            }
          ]
        },
        {
          key: 13,
          iow_description: "Sub-head",
          unit: null,
          rate: null,
          children: [
            {
              key: 131,
              iow_description: "Sub-head",
              unit: null,
              rate: null,
              children: [
                {
                  key: 1311,
                  iow_description: "Sub-head",
                  unit: "each",
                  rate: 200.0
                },
                {
                  key: 1312,
                  iow_description: "Sub-head",
                  unit: "sq.m",
                  rate: 200.0
                }
              ]
            }
          ]
        }
      ]
    }
  ]
};

最佳答案

你需要递归

const updateState = (children, key, newData) => {
  return children.map(item => {   
     if(item.children) {
       item.children = updateState(item.children, key, newData);
     }

    return item.key === key ? Object.assign({}, item, newData) : item;
  });
};
state.iow = updateState(state.iow, 131, {iow_description: "new value", rate: 123})

关于javascript - 如何更新这样的嵌套状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58512740/

相关文章:

javascript - 如何在 ReactJS 中验证输入类型 ="number"?

javascript - 如何避免 React fetch API 替换 url

c - 无法在 C 中传递 2D char 数组(似乎仅传递第一个索引)

c - 错误地初始化多维数组和内存

C - 全局与局部多维数组

javascript - 如何在 ajax 上传递带有表单序列化数据的附加数据?

php - 使用 jquery 每 X 秒从 phpfile 获取内容?

javascript - 将 React 组件转换为 Typescript?

javascript - 如何摆脱字符串文字中的多余空格?

javascript - 为什么这个表达式在 javaScript 中返回 2?