简体   繁体   English

解析 json 对象以比较其中的项目

[英]parse json object to compare the items in it

I have a json object structured like this:我有一个结构如下的 json 对象:

{

  "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.我想要做的是解析这个对象并比较一个输入字符串,与"catNames""dogNames""goldfishNames" ,如果两者匹配,比如说catNames ,我想从catNames数组中打印一个随机元素. 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)]);
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM