代码之家  ›  专栏  ›  技术社区  ›  Bruno Francisco

遍历递归数组并更新

  •  0
  • Bruno Francisco  · 技术社区  · 2 年前

    我正在尝试遍历一个数组,并在找到它时更新它。我在谷歌和SO上搜索过,但我想我没有使用正确的关键字来完成这项工作。

    问题

    我有以下目标:

    const form = {
      uuid: "ff17fd11-3462-4111-b083-7ff36b391c61",
      type: "form",
      items: [
        {
          uuid: "0b2dcf80-a376-4b3d-9491-0875ec24d6f7",
          type: "page",
          items: [
            {
              uuid: "23a8db85-4125-43db-ae04-d1243738972c",
              title: "Prepared by",
            },
            {
              uuid: "fb3898e0-c250-4dde-8b5c-cd2c99d181e9",
              title: "Completed at",
            }
          ],
          params: { header: true, collapsed: true }
        },
        {
          title: "",
          uuid: "e0d9d8c4-c064-4088-aad3-235b6ea1a6a1",
          type: "page",
          items: [
            {
              uuid: "73f97b99-9788-4748-82c6-7b62169f44fe",
              title: "you have been rickrolled",
            },
            {
              uuid: "46e7264c-7e95-4bbf-a4e7-7b7ab2d1ad88",
              type: "conditional_section",
              items: [
                {
                  uuid: "58e5e845-d18e-4c7e-9739-a387b8144d3c",
                  params: {
                    title: null,
                  },
                }
              ],
          ],
        }
      ]
    };
    

    给定以下对象,我想在数组中找到这个对象(由 uuid )并用新的替换它:

                                  👇 Heres the uuid that identifies the unique element in the array
    const updatedObject = { uuid: "58e5e845-d18e-4c7e-9739-a387b8144d3c", params: { title: "new title" } };
    
    findFormItem(form.items, updatedObject);
    

    到目前为止我所尝试的

    我创建了一个递归函数来更新数组,但由于某种原因,该项没有被更新:

    const findFormItem = (arr, item, parent = null) =>
      arr.reduce((acc, _item) => {
        if (acc) {
          return acc;
        }
    
        if (_item.uuid === item.uuid) {
          _item = item;
        }
    
        if (_item.items) {
          return findFormItem(_item.items, item, _item);
        }
    
        return acc;
      }, null);
    
    

    提问

    如何在不返回新副本的情况下更新数组/对象?我正在寻找一种不改变物体形状的解决方案。对象应保持原样,只更新传递给的值 findFormItem 功能

    codesandbox

    0 回复  |  直到 2 年前
        1
  •  1
  •   lbsn    2 年前

    如果你想更改原始数组,你可以直接使用 forEach 并在给定的位置替换对象 index :

    const findFormItem = (arr, item) => {
      arr.forEach((element, index, arr) => {
        if (element.uuid === item.uuid) {
          arr[index] = item;
        }
        if (element.items) {
          findFormItem(element.items, item);
        }
      });
    };