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

Time:07-23

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?

CodePudding user response:

Solution

You could use the "Array.find" method

Example

Stackblitz Snippet

CodePudding user response:

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)

CodePudding user response:

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');
  • Related