1

I am trying to solve my last issue with my reduce function to turn a nested JSON object into a flat list to enable easier searching.

Taking the JSON Below

    {
  "MovementPatterns": [
    {
      "Id": "",
      "Name": "Warm-up",
      "Exercises": [
        {
          "Id": "",
          "Name": "Lizard Stretch",
          "Level": 1,
          "EquipmentRequired": ""
        },
        {
          "Id": "",
          "Name": "Pigeon Stretch",
          "Level": 1,
          "EquipmentRequired": ""
        },
        {
          "Id": "",
          "Name": "Core Hold",
          "Level": 1,
          "EquipmentRequired": ""
        },
        {
          "Id": "",
          "Name": "Superman",
          "Level": 1,
          "EquipmentRequired": ""
        }
      ]
    },
    {
      "Name": "Horizontal Push",
      "Id": "",
      "Exercises": [
        {
          "Id": "",
          "Name": "Wall Push-up",
          "Level": 0,
          "VideoUrl": "",
          "EquipmentRequired": ""
        },
        {
          "Id": "",
          "Name": "Push-up",
          "Level": 1,
          "EquipmentRequired": ""
        },
        {
          "Id": "",
          "Name": "Tap Push-up",
          "Level": 2,
          "EquipmentRequired": ""
        },
        {
          "Id": "",
          "Name": "Explosive Push-up",
          "Level": 3,
          "EquipmentRequired": ""
        }
      ]
    }
  ]
}

I have used the following code:

const exercises = data.MovementPatterns.reduce(
  (a, {Exercises}) => [...a, ...Exercises, ...a],
  [],
);

To flattern all the exercises from each movement pattern into a pure list of exercises...This is great, but I now need to INCLUDE in that JSON for each exercise the PARENT Movement Pattern ID e.g.

[
        {
          "Id": "",
          "Name": "Lizard Stretch",
          "Level": 1,
          "MovementPatternId": 1,
          "EquipmentRequired": ""
        },
....
        {
          "Id": "",
          "Name": "Wall Push-up",
          "Level": 1,
          "MovementPatternId": 2,
          "EquipmentRequired": ""
        },
]

Can someone please help me figure out how to do this with my reduce function :)

Thanks

2

1 Answer 1

4

You're almost close. Just append parent's Id as MovementPatternId to the each element of Exercises.

const exercises = ab.MovementPatterns.reduce(
  (a, { Exercises, Id }) => [
    ...a,
    ...Exercises.map(e => ({ ...e, MovementPatternId: Id }))
  ],
  []
);
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.