JLI_98
JLI_98

Reputation: 355

Iterating through an array of objects with nested array and objects to add my own object

I have this array of nested objects and arrays:

const myArr = [
  {
    workoutName: "workout1",
    exercises: [
      {
        exerciseName: "Bench Press",
        sets: [
          {
          // some props and vals
          },
        ]
      },
      {
        exerciseName: "Deadlift",
        sets: [
          {
          // some props and vals
          },
        ]
      },
      {
        exerciseName: "Squat",
        sets: [
          {
          // some props and vals
          },
        ]
      },
      // more exercises
    ]
  }
]

const compareVal = "Deadlift";
const mySetObj = {//some data}

I want to iterate through the exercises array of objects and compare the exerciseName value for each object with the compareVal for a match. If it does match, I want to be able to add myObj as a value to that object's setsarray. Each of the exerciseName values are unique, so it would not be necessary to iterate through all of the exercises after finding a match.

Is there a way I can achieve this elegantly?

Upvotes: 1

Views: 66

Answers (1)

Nick
Nick

Reputation: 16576

Seems like an array find method would be sufficient. Note that, in this solution, we use a forEach loop on the myArr array since it seems you might want to do this for each routine.

myArr.forEach(routine => {
  const ex = routine.exercises.find(e => e.exerciseName === compareVal);
  ex.sets.push(mySetObj);
})

Update: Since you just need this for myArr[0], this can be simplified as follows:

const ex = myArr[0].exercises.find(e => e.exerciseName === compareVal);
ex.sets.push(mySetObj);

And here it is working:

const myArr = [
  {
    workoutName: "workout1",
    exercises: [
      {
        exerciseName: "Bench Press",
        sets: [
          {
          // some props and vals
          },
        ]
      },
      {
        exerciseName: "Deadlift",
        sets: [
          {
          // some props and vals
          },
        ]
      },
      {
        exerciseName: "Squat",
        sets: [
          {
          // some props and vals
          },
        ]
      },
      // more exercises
    ]
  }
]

const compareVal = "Deadlift";
const mySetObj = { some: "data" };

const ex = myArr[0].exercises.find(e => e.exerciseName === compareVal);
ex.sets.push(mySetObj);

console.log(myArr);

Upvotes: 1

Related Questions