parse json object to compare the items in it

Viewed 58

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?

1 Answers

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)]);
    });
Related