ternt
ternt

Reputation: 31

Faker.js random word with choices

I'm trying to use faker.js to generate some random words, but I want it to choose between a few choices.

faker.random.word()

I tried something like this

faker.random.word({constraints: ['','','']})

This didn't work, and I could be way off since this was just a straight up guess. I tried looking for documentation on it but couldn't find any. Any suggestions?

Upvotes: 2

Views: 5570

Answers (4)

Jonalogy
Jonalogy

Reputation: 970

Since Faker v6.3.0, the following 2 methods should do the trick:

  1. faker.helpers.arrayElement (doc)
  2. faker.helpers.arrayElements (doc)

Upvotes: 3

RenaudC5
RenaudC5

Reputation: 3829

You can generate a number between 0 and the number of words you have and access the words using an array

const words = ["foo", "bar", "baz"]
const randomNumber = faker.datatype.number({
    'min': 0,
    'max': words.length - 1
});
console.log(words[randomNumber])

Upvotes: 3

soroush gh
soroush gh

Reputation: 11

i was looking for same issue in php , the php way is this :

echo $faker->randomElements(['a', 'b', 'c', 'd', 'e']);

['c']

Upvotes: 0

Mohammad Yaser Ahmadi
Mohammad Yaser Ahmadi

Reputation: 5051

I have not seen anything like this in faker module but you can using uniqueNamesGenerator module, check the documentation

const { uniqueNamesGenerator } = require('unique-names-generator'); ;
 
const colors = [
  'Green', 'Red', 'Yellow', 'Black'
]
 
const characterName =  uniqueNamesGenerator({
  dictionaries: [colors],
  length: 1
});

console.log(characterName)

Upvotes: 0

Related Questions