Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parse json object to compare the items in it

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?

like image 312
paolo garrasi Avatar asked Jun 05 '26 09:06

paolo garrasi


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)]);
    });
like image 158
Will Evers Avatar answered Jun 07 '26 23:06

Will Evers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!