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?
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?
Share Improve this question asked Feb 4, 2021 at 17:48 terntternt 311 silver badge3 bronze badges4 Answers
Reset to default 4Since Faker v6.3.0, the following 2 methods should do the trick:
faker.helpers.arrayElement
(doc)faker.helpers.arrayElements
(doc)
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])
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)
i was looking for same issue in php , the php way is this :
echo $faker->randomElements(['a', 'b', 'c', 'd', 'e']);
['c']