0

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?

2

3 Answers 3

2

Solution

You could use the "Array.find" method

Example

Stackblitz Snippet

3
  • This will return an ARRAY including all the elements that match the condition. OP wants only the first match so using .find will be much better since it will stop iterating when finding the first match and it returns the element itself instead of an array with the element
    – Bimoware
    Commented Jul 22, 2022 at 14:50
  • Sorry, made a typo. I meant find, will edit Commented Jul 22, 2022 at 15:07
  • Oh I see perfect then
    – Bimoware
    Commented Jul 22, 2022 at 15:08
2
const plan =  [ { "id": "price_aehdw424i7rxyeqiquedwuy", 
    "name": "Monthly Plan", 
    "price": 2900, 
    "interval": "month", 
    "currency": "usd",
  }, 
 { "id": "price_46r34dgqn4d7w4fdw3476r323", 
   "name": "Yearly Plan", 
   "price": 29900, 
   "interval": "year", 
   "currency": "usd",
 } ]

const filtered  = plan.find((x)=>x.id === yourId)
0
let obj = [ { "id": "price_aehdw424i7rxyeqiquedwuy", 
    "name": "Monthly Plan", 
    "price": 2900, 
    "interval": "month", 
    "currency": "usd",
  }, 
 { "id": "price_46r34dgqn4d7w4fdw3476r323", 
   "name": "Yearly Plan", 
   "price": 29900, 
   "interval": "year", 
   "currency": "usd",
 } ];
 
 search_id = "price_aehdw424i7rxyeqiquedwuy";

 let filtr = obj.filter(function(element){
     if(element.id==search_id) return element
 });
 
 
console.log (filtr.length?filtr[0]:'Not Found');

Not the answer you're looking for? Browse other questions tagged or ask your own question.