0

I have the following cardInfo.json that I made and I want to use node.js to randomly select the card and its information and store it in variables.

{
    "card1": {
        "cardNumber": "",
        "cvv": "",
        "expMonth":"",
        "expDay":"",
        "name":""
        },
    "card2": {
        "cardNumber": "",
        "cvv": "",
        "expMonth":"",
        "expDay":"",
        "name":""
    }
}

2 Answers2

-1

You can use Math.random() function to generate a random integer and return a random card something like below.

const cards = {
  "card1": {
    "cardNumber": "1",
    "cvv": "1",
    "expMonth": "1",
    "expDay": "1",
    "name": "1"
  },
  "card2": {
    "cardNumber": "2",
    "cvv": "2",
    "expMonth": "2",
    "expDay": "2",
    "name": "2"
  },
  "card3": {
    "cardNumber": "3",
    "cvv": "3",
    "expMonth": "3",
    "expDay": "3",
    "name": "3"
  },
  "card4": {
    "cardNumber": "4",
    "cvv": "4",
    "expMonth": "4",
    "expDay": "4",
    "name": "4"
  },
  "card5": {
    "cardNumber": "5",
    "cvv": "5",
    "expMonth": "5",
    "expDay": "5",
    "name": "5"
  },
  "card6": {
    "cardNumber": "6",
    "cvv": "6",
    "expMonth": "6",
    "expDay": "6",
    "name": "6"
  }
};


const getRandomInt = () => {
  const max = Object.keys(cards).length;
  return Math.floor(Math.random() * Math.floor(max));
}

const getCard = () => {
  const num = getRandomInt();
  const cardKey = Object.keys(cards)[num];
  return cards[cardKey];
}

console.log(getCard())
SpiritOfDragon
  • 1,404
  • 2
  • 15
  • 27
-1

I would probably place the cards in an Array, it would be easier ... if not, if the name is actually cardXX you can do the same:

const cards = { ... }
const max = Object.keys(cards).length
const random = Math.floor(Math.random()*(max)+1)

and then

const randomCard = cards[`card${random}`]

here's an example

balexandre
  • 73,608
  • 45
  • 233
  • 342