我从另一个名为{ groupData }的文件导入数据(所以从技术上讲,我认为它是一个包含对象数组的对象)。目前,数组只包含5个对象,但它的长度是可变的,可以包含更多对象。每个对象看起来如下所示:
{
name: "A Name",
img: "https://imgURL.goes.here",
details: "This is a fun group about fun things.",
likes: 45,
},我的目标是从数组中获取每个对象,修改数据,并将这些对象放入一个称为"groups“的空有状态数组中。我希望每个对象在进入新的"groups“数组之前看起来像这样:
{
name: "A Name",
img: "https://imgURL.goes.here",
details: "This is a fun group about fun things.",
hasNotification: Boolean,
userIsAdmin: Boolean,
},我想过解构数组,但如果要向数组中添加内容,则此解决方案不可伸缩:
const [groupZero, groupOne, groupTwo, groupThree, groupFour] = groupData;实现这一目标的最有效方法是什么?谢谢你!!
发布于 2020-08-27 22:09:19
由于缺乏上下文,我不能确切地确定您需要什么。但是您可以使用for循环来迭代数组中的每个对象。
如果可以调整现有数据:
for (data of groupData){
delete data.likes;
data.hasNotification = true; // or false
data.userIsAdmin = true; // or false
}
setState(groupData); // if you are using useState hooks如果您不想更改原始数据:
// create a deep clone of groupData
const newGroup = JSON.parse(JSON.stringify(groupData));
for (data of newGroup){
delete data.likes;
data.hasNotification = true; // or false
data.userIsAdmin = true; // or false
}
setState(newGroup);如果使用的是类组件,请相应地调整setState部分
https://stackoverflow.com/questions/63606039
复制相似问题