【问题标题】:How do I update one of the array fields?如何更新数组字段之一?
【发布时间】:2021-09-26 07:05:21
【问题描述】:

我有一个这样的数组:

a=[{id:1 , operand:2 ,children:[{a:1]{b:2}]

当我想添加一个新字段时,我会这样做:

   const [items, setItems] = useState(a);
    
      const gettableData = (value) => {
        let operanList = items;
  let repeatListError = tableData.filter((i) => i.operandId === value.operandId);
    if (!repeatListError.length > 0) operanList.push(value);
        setTableData(operanList);
      };

每次单击按钮时都会调用此方法。 我想在添加新对象时检查操作数,如果只有更新children.like:

value=[{id:1 , operand:2 ,children:[{a:1]{b:2}{c:3}{d:4}]

【问题讨论】:

  • 您是否检查过 JavaScript 的 Array 方法(如 map、filter、find 等)的工作原理?
  • 是的。但是如果操作数存在,我希望它只更新孩子。我更新了我的问题

标签: javascript arrays reactjs react-hooks


【解决方案1】:

第一个重新格式化值,如下所示。您所拥有的语法不正确:

  const value=[{id:1 , operand:2 ,children:{a:1,b:2,c:3,d:4}}]

您可以通过以下方式更改数组中对象内的子项:

  const list = [
    { id: 1, operand: 2, children: { a: 1, b: 2, c: 3, d: 4 } },
    { id: 2, operand: 3, children: { a: 1, b: 2, c: 3, d: 4 } },
  ];

  let newList = [...list];
  let updatedChildren = { ...newList[1].children, e: 5, f: 6 };
  let updatedItem = { ...newList[1], children: updatedChildren };
  newList.splice(1, 1, updatedItem);

  console.log(newList);

  setState(newList);

你创建了一个新的数组实例。更新您想要的项目的 children 属性(在这种情况下我选择了 1 )。然后更新数组中的整个对象(它包含 id & 操作数和 children )。最后通过用新项目替换原始项目来改变新列表。在 splice 方法中,请记住第二个数字必须始终为 1,因为它将删除一个项目,而给定的第一个数字应该是需要更改的项目的索引(在这种情况下,我们选择了一个)。然后您可以继续根据需要设置状态,因为您有一个新的更新列表。

【讨论】:

    【解决方案2】:

    我发现您的代码中使用的变量名称有些不一致,例如tableData 在哪里? items 是状态的一部分吗?

    我不明白 children 是一个对象数组还是只是一个具有键值对的对象。

    无论如何,正如我在评论中提到的,实现这一目标的最简单方法是使用 map。将其视为通用实现并尝试在您的代码中使用它。

    const a=[{id:1 , operand:2 ,children:[{a:1]{b:2}] // What is the data stucture of children? Is it array of objects or just object?
    
    const [items, setItems] = useState(a);
    const gettableData = (value) => {
      
      // creating a copy is not required as map will return a new array.
      // map => filter + modify, so use map
      
      let updatedList = tableData.map((i) => {
        if (i.operandId === value.operandId) {
          // match found, so update children
          return {
             ...i,                  // first, copy everything from i
             children: [            // then update children, and since children is an array of objects
               ...i.children,       // first copy every key of i's children
               ...value.children    // then copy value's children
             ]
          }
        }
        return i;     // no match? return i as it is.
      });
    
      setItems(updatedItems)
    

    【讨论】:

      【解决方案3】:

      你必须把数组放在另一个变量中,告诉它如果它有孩子,它会在children字段中记住它并为它设置一个新值。

      【讨论】:

      • 最好添加代码来澄清你的答案:)
      猜你喜欢
      • 2018-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-14
      • 1970-01-01
      • 1970-01-01
      • 2021-01-15
      相关资源
      最近更新 更多