Find a value in an array inside other array with lodash

这一生的挚爱 提交于 2019-12-06 15:41:17

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.

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

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