1

Consider I have this array of objects:

const workouts = [
  {
    workoutId: 1,
    username: "John Doe",
    exercises: [
      {
        exerciseId: 10,
        sets: [
          {
            setId: 100
          },
          {
            setId: 101
          },
          // more set objects
        ]
      },
      {
        exerciseId: 11,
        sets: [
          {
            setId: 102
          },
          // more set objects
        ]
      },
      // more exercise objects
    ]
  },

  {
    workoutId: 2,
    username: "James Smith",
    exercises: [
      {
        exerciseId: 12,
        sets: [
          {
            setId: 103
          }
        ]
      }
    ]
  },
  // more workout objects
]

I need to delete a specific object (set) from this array, depending on two values passed from the user. These values will be a exerciseId and a setId. As the actual array from my project is larger than this example, I also get the context of a user to narrow down the search criteria (hopefully improving the speed at which it executes?). I currently have this function:

function deleteSet(workouts, exerciseId, setId, context) {
  const { username } = checkAuth(context) // Checks for logged in user and gets the username from it.
  const userWorkouts = workouts.find( { username: username });
}

So far, I know that userWorkouts will retrieve all the workouts with the logged in user's username and store it as an array. Consider that setId = 101 and exerciseId = 10, how can I achieve only deleting the set object that matches these two inputs from the userWorkouts array?

JLI_98
  • 345
  • 2
  • 10
  • Is your goal to only delete, in your example, `{ setId: 101 }` and leave `{ setId: 100 }` or do you want to delete the full object? – Y. Gherbi Jan 22 '21 at 14:01
  • Just `{ setId: 101 }` – JLI_98 Jan 22 '21 at 14:02
  • @HereticMonkey it does not, that example does not traverse nested objects. – JLI_98 Jan 22 '21 at 14:06
  • @mplungjan thanks for pointing this out, I have corrected this. – JLI_98 Jan 22 '21 at 14:08
  • You might need to look for separate help on traversing nested objects, like [How can I access and process nested objects, arrays or JSON?](https://stackoverflow.com/q/11922383/215552). – Heretic Monkey Jan 22 '21 at 14:10
  • 1
    Personally, I would fix it like this: https://codesandbox.io/s/fragrant-bush-lkd67?file=/src/index.js. This way the deleteSet function just returns a new list – Y. Gherbi Jan 22 '21 at 14:23

0 Answers0