守著一只汪
2023-07-06 14:51:17
我有一個結(jié)構(gòu)如下的 json 對象:{ "catNames" : ["a1", "a2", "a3", "a4"], "dogNames" : ["b1", "b2", "b3", "b4"], "goldfishNames" : ["c1", "c2", "c3", "c4"]}我想做的是解析這個對象并將輸入字符串與 , "catNames","dogNames"進(jìn)行比較"goldfishNames",如果兩者匹配,比方說catNames,我想從catNames數(shù)組中打印一個隨機(jī)元素。我完全迷失了,我該怎么辦?
1 回答

慕雪6442864
TA貢獻(xiàn)1812條經(jīng)驗 獲得超5個贊
迭代對象的鍵,查看該鍵的值是否包含匹配的名稱,如果包含,您可以在隨機(jī)索引處記錄數(shù)組中的名稱。
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
提交
取消