0

I have an API that is going to be spitting out a few dozen objects, each one containing a promo_url and a promo_number, in order to do dynamic number swapping on my Gatsby site. Like so:

 [{
    "promo_url": "/promo1",
    "promo_number": "665-894-3142"
  },
  {
    "promo_url": "/promo2",
    "promo_number": "493-441-7386"
  },
  {
    "promo_url": "/promo3",
    "promo_number": "549-823-5785"
  },
  {
    "promo_url": "/promo4",
    "promo_number": "553-747-1261"
  },
  {
    "promo_url": "/promo5",
    "promo_number": "253-741-2776"
  }]

Essentially, what I need to do is find and set the user's referral URL, check through the data, find the URL that matches it, and then pass the related phone number to my components through a context, however I have no idea how to check the objects, find the matching URL, and then pass the related phone number. Does anyone have any ideas on how/where I should begin?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Jesse Winton
  • 568
  • 10
  • 33
  • 1
    Does this answer your question? [Find object by id in an array of JavaScript objects](https://stackoverflow.com/questions/7364150/find-object-by-id-in-an-array-of-javascript-objects) – Heretic Monkey Oct 21 '20 at 20:40

1 Answers1

0

You could use a reduce function here to return the promo number. The reduce function is great at taking data and simplifying it down. Here I am just iterating through it similar to a filter but what is cool with reduce is you can see defaults for the return and I find it more readable sometimes.

const apiResults = [
  {
   "promo_url": "/promo1",
    "promo_number": "665-894-3142"
  },
  {
    "promo_url": "/promo2",
    "promo_number": "493-441-7386"
  },
  {
    "promo_url": "/promo3",
    "promo_number": "549-823-5785"
  },
  {
    "promo_url": "/promo4",
    "promo_number": "553-747-1261"
  },
  {
    "promo_url": "/promo5",
    "promo_number": "253-741-2776"
  }
]
const referralUrl = "/promo5"

const promoNumber = apiResults.reduce((promoNumber, result) => {
  const IS_USER_PROMO = referralUrl === results.promo_url
  if(IS_USER_PROMO) {
    return result.promo_number
  }
  return promoNumber
}, "")
Tall Paul
  • 2,398
  • 3
  • 28
  • 34