【问题标题】:How to add properties to an object that is inside an array of objects with useState hook如何使用 useState 钩子向对象数组内的对象添加属性
【发布时间】:2020-09-24 03:05:34
【问题描述】:

我有一个从 useState 钩子创建的对象数组:

const [arrayOfObjects, setArrayOfObjects] = useState([]);

setArrayOfObjects([{id:1}, {id:2}, {id:3}]);

如何通过 setArrayOfObjects 函数为每个对象添加一个属性,使其成为:

[
 {
  id:1,
  name: "one",
 },
 {
  id:2,
  name: 'two',
 },
 {
  id:3,
  name: 'three',
 },
]

谢谢!

【问题讨论】:

  • 嗨,到目前为止,您尝试了什么?

标签: arrays reactjs object react-hooks


【解决方案1】:

为此,您可以在数组类型中使用映射运算符。这将返回一个新数组,并将您的数据转换(映射)为其他类似的东西:

let newarrayOfObjects = arrayOfObjects.map(e => {
return {
  id: e.id,
  name: someVariableWithTheName,
 }
});
setArrayOfObjects(newarrayOfObjects);

如果你需要元素的索引来做某事,map方法实际上有两个参数,第一个是元素,第二个是元素的索引,所以代码可以这样使用:

let newarrayOfObjects = arrayOfObjects.map(e, index => {
return {
  id: e.id,
  name: index,
 }
});
setArrayOfObjects(newarrayOfObjects);

【讨论】:

    【解决方案2】:

    定义数组添加和使用JavaScript数组映射函数。

    const additionalArr = [{name: 'one'}, {name: 'two'}, {name: 'three'}];
    const newArrayOfObjects = arrayOfObjects.map((obj, idx) => ({
      ...obj,
      ...additionalArr[idx]
    }));
    
    setArrayOfObjects(newArrayOfObjects);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-09
      • 1970-01-01
      • 2022-08-16
      • 1970-01-01
      • 2011-11-09
      • 2019-12-11
      • 1970-01-01
      相关资源
      最近更新 更多