'Return the key from object NOT array JavaScript [duplicate]
I searched a lot on the internet and didn't find any answer to solve my problem.
I have an object with several keys and values.
const replies = {
"Hello": ['Hi', 'Whats up', 'Aloha'],
"See you": ['Goodbye', 'exit']
};
My string is
Var sentence = "Hi my friend";
I would like a function that returns the key of "replies" if the "sentence" contains some value from it. Something like:
function search(replies, sentence){
var reply = sentence.includes(replies);
return reply //output is Hello key
}
Solution 1:[1]
Explanations throughout the code below.
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Louys Patrice Bessette |
