I have an array such as:
var db = [{
"words": ["word1a", "word1b", "word1c"],
"answer": "answer1"
}, {
"words": ["word2a", "words2b"],
"answer": "answer2"
}]
I'm using lodash on node.js to check values in an array. I want to search words and return an response. For example, if I search "word1a", the response is "answer1"
I try:
var e = _.find(db, function(o){
o.words === "say"
});
console.log(e);
But I cant find a result;
Obviously, I get undefined because I'm comparing an exactly value. How can I get the value?
Well, you're also getting undefined because you also aren't returning the o.words === "say" comparison.
But you're right, that comparison wouldn't work in this case. You should use something like _.some inside the _.find callback:
var e = _.find(db, function(o) {
return _.some(o.words, function(word) {
return word === 'say';
});
});
This should give you the object back (or undefined, if none are found). If you want answer specifically, you'll still have to pull it out of the object.
Here's a working fiddle. Note that you should also put in some extra protection against undefined objects / properties. I'll leave that up to you, though.
An ES6 version:
const term = "word1b";
const res = _(db)
.filter(item => item.words.indexOf(term) !== -1)
.first()
.answer;
As mentioned in another answer, you should still check for existence pre-grabbing the .answer value from the returned object.
来源:https://stackoverflow.com/questions/36415316/find-a-value-in-an-array-inside-other-array-with-lodash