Skip to content
Advertisement

How to access, merge and collect array values within a nested data structure by different criteria?

I have below array of objects. As you can see, i have 2 runTypes named VEGGIES and FRUITS. Each runType will have a list of verticals to it. For e.g. VEGGIES has SPINACH, TOMATO, ONION and FRUITS has APPLE, BANANA, GRAPES

JavaScript

In my case, i want to extract these vertical values and put them in an array. In case of regular array of objects, we can achieve the above task by using this code.

JavaScript

But my code has array of objects inside an array of object. Can someone please let me know how to achieve these 3 scenarios

  1. Scenario 1- Get all the verticals for both runType. Result should be [SPINACH, TOMATO, ONION, APPLE, BANANA, GRAPES]
  2. Scenario 2- get all verticals for runType = ‘VEGGIES’. Result should be [SPINACH, TOMATO, ONION]
  3. Scenario 3- get all verticals for runType = ‘FRUITS’. Result should be [APPLE, BANANA, GRAPES]

Can someone pls shed some light on this particular data.

Advertisement

Answer

In addition to map the OP also might have a look into flatMap and findreduce is also worth a try …

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement