Skip to content
Advertisement

How to filer an array of objects and return only one object based on a specific value

I have an array containing two plan objects:

[ { "id": "price_aehdw424i7rxyeqiquedwuy", 
    "name": "Monthly Plan", 
    "price": 2900, 
    "interval": "month", 
    "currency": "usd",
  }, 
 { "id": "price_46r34dgqn4d7w4fdw3476r323", 
   "name": "Yearly Plan", 
   "price": 29900, 
   "interval": "year", 
   "currency": "usd",
 } ]

What I am trying to do is use a value (customerPlanId) to find the correct plan by matching it to the plan.id and then just return the correct plan, like below:

{ "id": "price_aehdw424i7rxyeqiquedwuy", 
    "name": "Monthly Plan", 
    "price": 2900, 
    "interval": "month", 
    "currency": "usd",
  }

I know I can map through the plans and filter for the correct plan, but then how can I return the correct plan object on its own?

Advertisement

Answer

Solution

You could use the “Array.find” method

Example

Stackblitz Snippet

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