如何在 JS 对象中搜索元素(构建不和谐机器人 - 不和谐.js)



>本质上,我需要检查输入是否在一个对象中,如果不是,则检查另一个对象。

我有一个包含数据的 CSV 文件,其中每行的第一列都有完整的国家/地区名称。

一个例子是:

英国,4,8,1,0

机器人从c.(国家名称或国家代码(获取数据,例如 c.ukc.unitedKingdom将是csv文件中的英国。

我添加了很多评论,希望它更容易阅读!

else if((msg.content.split('.')[1] != null)){
let arr1 = {
"AD":"Andorra",
"AE":"U A E",
}
let arr11 = Object.fromEntries(Object.entries(arr1).map(e=>e.reverse())); //reversed original object to allow for full country names to be inputted
let arr2 = JSON.parse(JSON.stringify(arr11).replace(/"s+|s+"/g,'"')); //strips of blank spaces to match input
var country = msg.content.split('.')[1]; //splits c.uk to ['c.','uk']
if(arr1[country]){ // checking if user inputted a string that is a country code
//EXECUTE on found in first array. e.g. user entered 'ad', and the program finds 'Andorra'
msg.channel.send('you entered **' + country + '** and the checking was **' + arr1[country] + '** [Using arr1]');
}
else if(arr2[country]){ //checking if user inputted country name
//EXECUTE on found unitedkingdom to UK - add .tolowerCase
msg.channel.send('you entered **' + country + '** and the checking was **' + arr2[country] + '** [Using arr2]');
} else {
msg.channel.send('else statement executed');
}

}

目前,这总是打印("else 语句已执行"(。

任何帮助将不胜感激 - 谢谢!

您尝试检查arr1[country],其中country可以处于不同的大小写中,例如arr1['uk'],当UK大写的对象中的 -key 时。

做这样的事情:

let arr1 = {
"AD":"Andorra",
"AE":"U A E",
}
// remove spaces from value, make it upper case and reverse
const makeObj = ([key, value]) => {
// array [VALUE, key]
let result = [value.toUpperCase().replace(/s/g, ''), key];
return result;
}
let arr2 = Object.fromEntries(Object.entries(arr1).map(makeObj)); // reverse object
arr1 = Object.assign(arr1, arr2); // make single object
let country = msg.content.split('.')[1].toUpperCase(); // requested country in upper case
if(arr1[country]){
msg.channel.send(country, arr1[country]);
} else {
msg.channel.send('else statement executed');
}

最新更新