使用lodash在其他数组内的数组中查找值 [英] Find a value in an array inside other array with lodash
问题描述
我有一个数组,例如:
var db = [{
"words": ["word1a", "word1b", "word1c"],
"answer": "answer1"
}, {
"words": ["word2a", "words2b"],
"answer": "answer2"
}]
我在node.js上使用lodash来检查数组中的值.我想搜索单词并返回响应.例如,如果我搜索"word1a",则响应为"answer1"
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"
我尝试:
var e = _.find(db, function(o){
o.words === "say"
});
console.log(e);
但是我找不到结果;
很显然,我不确定,因为我正在比较一个确切的值.我如何获得价值?
Obviously, I get undefined because I'm comparing an exactly value. How can I get the value?
推荐答案
好吧,您也得到了undefined
,因为您也没有返回o.words === "say"
比较.
Well, you're also getting undefined
because you also aren't returning the o.words === "say"
comparison.
但是你是对的,这种比较在这种情况下是行不通的.您应该在_.find
回调中使用类似_.some
的内容:
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';
});
});
这应该给您对象(如果未找到,则为未定义).如果要专门使用answer
,则仍然必须将其从对象中拉出.
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.
这是工作小提琴.请注意,您还应该对undefined
对象/属性进行一些额外的保护.不过,我将由您决定.
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.
这篇关于使用lodash在其他数组内的数组中查找值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!