1

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?

3
  • 1
    It looks like myArr is an array itself. Do you need to do this for each workout routine, or just for myArr[0]? Commented Dec 20, 2020 at 23:33
  • Just myArr[0], the array will not have more than one workout routine. Commented Dec 20, 2020 at 23:36
  • 1
    OK, I'll update my answer Commented Dec 20, 2020 at 23:36

1 Answer 1

1

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.