I have a json object structured like this:
{
"catNames" : ["a1", "a2", "a3", "a4"],
"dogNames" : ["b1", "b2", "b3", "b4"],
"goldfishNames" : ["c1", "c2", "c3", "c4"]
}
what I would like to do is to parse this object and compare an input string, with "catNames", "dogNames", "goldfishNames", if the two match, let's say catNames, I want to print a random element from the catNames array. I'm completely lost ,how can I do this?
Iterate over the keys of the object, see if the value for that key contains a matching name, and if it does you can log a name from the array at a random index.
const jsonObject ={
"catNames" : ["a1", "a2", "a3", "a4"],
"dogNames" : ["b1", "b2", "b3", "b4"],
"goldfishNames" : ["c1", "c2", "c3", "c4"]
};
const input = 'a1';
Object.keys(jsonObject).forEach(key =>{
const nameArr = jsonObject[key];
if(nameArr.includes(input))
console.log(nameArr[Math.floor(Math.random() * nameArr.length)]);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With