Mills
Mills

Reputation: 57

object.assign is overwriting all objects in my array with duplicate information

I am trying to add an identifier key to each exercise object by using the object.assign, however, if I add multiples of the same object.

The new object.assign overrides the key(directId) for all with the same name. I've tried using loops, maps, add the timestamp to the key to see if uuidv1 gives the same keyid if objects are exactly the same, but I don't believe it is.

It seems like its an issue with object.assign.

The function runs every time I onpress a new object and uuidv1() is a unique key generator.

Unsure what to try next.

  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: ]

a unique key should be added via object assign before it gets passed on to the react state.

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: ]

Upvotes: 2

Views: 208

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386660

You could assign the values to an empty object to prevent same references to the result array.

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

Upvotes: 2

Related Questions