我在互联网上搜索了很多,没有找到任何解决问题的答案。
我有一个包含多个键和值的对象。
const replies = {
"Hello": ['Hi', 'Whats up', 'Aloha'],
"See you": ['Goodbye', 'exit']
};
我的字符串是
Var sentence = "Hi my friend";
我想要一个返回键"的函数;回复";如果";句子";包含其中的一些值。类似于:
function search(replies, sentence){
var reply = sentence.includes(replies);
return reply //output is Hello key
}
下面整个代码的解释。
const replies = {
"Hello": ['Hi', 'Whats up', 'Aloha'],
"See you": ['Goodbye', 'exit']
};
var sentence = "Hi my friend";
// Get the replies keys in an array
let keys = Object.keys(replies);
// Then, each key holds an array... Loop it to compare against the sentance
let hits = keys.map(function(key){
return replies[key].map(function(word){
return sentence.includes(word) ? key : null
})
})
// You will get an array structured like replies
console.log(hits)
// Flatten it and filter out the nulls
let result = hits.flat().filter(item=>item)
// Your expected result as a array
console.log(result)