gpt4 book ai didi

javascript - object.assign 正在用重复信息覆盖我数组中的所有对象

转载 作者:行者123 更新时间:2023-11-29 23:16:23 24 4
gpt4 key购买 nike

我正在尝试使用 object.assign 为每个练习对象添加一个标识符键,但是,如果我添加多个相同的对象。

新的 object.assign 覆盖了所有同名的 key(directId)。我试过使用循环、映射、将时间戳添加到 key 以查看如果对象完全相同,uuidv1 是否给出相同的 keyid,但我不相信它是。

这似乎是 object.assign 的问题。

每当我按下一个新对象时,该函数就会运行,而 uuidv1() 是一个唯一的 key 生成器。

不确定接下来要尝试什么。

  saveDataToWorkout = obj => {
const objWithId = Object.assign(obj, { directId: uuidv1() });
this.setState({
pendingSavedArr: [...this.state.pendingSavedArr, objWithId]
});
};

04:16:45: Array [
04:16:45: Object {
04:16:45: "avatarURL": 16,
04:16:45: "difficulty": "Easy",
04:16:45: "directId": "d50d5310-c7ad-11e8-a726-e942788f9851",
04:16:45: "equipment": "Machine",
04:16:45: "estimatedTime": 5,
04:16:45: "muscleGroup": "Shoulders and Traps",
04:16:45: "title": "Leverage Shrug",
04:16:45: },
04:16:45: Object {
04:16:45: "avatarURL": 16,
04:16:45: "difficulty": "Easy",
04:16:45: "directId": "d61e4de0-c7ad-11e8-a726-e942788f9851",
04:16:45: "equipment": "Machine",
04:16:45: "estimatedTime": 5,
04:16:45: "muscleGroup": "Shoulders and Traps",
04:16:45: "title": "Smith Machine Shrug",
04:16:45: },
04:16:45: ]

在传递给 react 状态之前,应该通过对象分配添加一个唯一的键。

04:16:46: Array [
04:16:46: Object {
04:16:46: "avatarURL": 16,
04:16:46: "difficulty": "Easy",
04:16:46: "directId": "d50d5310-c7ad-11e8-a726-e942788f9851",
04:16:46: "equipment": "Machine",
04:16:46: "estimatedTime": 5,
04:16:46: "muscleGroup": "Shoulders and Traps",
04:16:46: "title": "Leverage Shrug",
04:16:46: },
04:16:46: Object {
04:16:46: "avatarURL": 16,
04:16:46: "difficulty": "Easy",
04:16:46: "directId": "d61e4de0-c7ad-11e8-a726-e942788f9851",
04:16:46: "equipment": "Machine",
04:16:46: "estimatedTime": 5,
04:16:46: "muscleGroup": "Shoulders and Traps",
04:16:46: "title": "Smith Machine Shrug",
04:16:46: },
04:16:46: Object {
04:16:46: "avatarURL": 16,
04:16:46: "difficulty": "Easy",
04:16:46: "directId": "d6924560-c7ad-11e8-a726-e942788f9851",
04:16:46: "equipment": "Dumbbell",
04:16:46: "estimatedTime": 5,
04:16:46: "muscleGroup": "Shoulders and Traps",
04:16:46: "title": "Smith Machine Behind the Back Shrug",
04:16:46: },
04:16:46: ]

最佳答案

您可以将值分配给一个空对象,以防止对结果数组进行相同的引用。

const objWithId = Object.assign({}, obj, { directId: uuidv1() });

关于javascript - object.assign 正在用重复信息覆盖我数组中的所有对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52642678/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com