我有一个结构如下的 json 对象:{ "catNames" : ["a1", "a2", "a3", "a4"], "dogNames" : ["b1", "b2", "b3", "b4"], "goldfishNames" : ["c1", "c2", "c3", "c4"]}我想做的是解析这个对象并将输入字符串与 , "catNames","dogNames"进行比较"goldfishNames",如果两者匹配,比方说catNames,我想从catNames数组中打印一个随机元素。我完全迷失了,我该怎么办?
1 回答
慕雪6442864
TA贡献1812条经验 获得超5个赞
迭代对象的键,查看该键的值是否包含匹配的名称,如果包含,您可以在随机索引处记录数组中的名称。
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)]);
});
添加回答
举报
0/150
提交
取消