Find a value in an array inside other array with lodash

霸气de小男生 提交于 2019-12-07 21:26:42

问题


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?


回答1:


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.




回答2:


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.

http://jsbin.com/kihubutewo/1/edit?js,console



来源:https://stackoverflow.com/questions/36415316/find-a-value-in-an-array-inside-other-array-with-lodash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!