使用 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 检查数组中的值。我想搜索字词和 return 回复。例如,如果我搜索 "word1a",则响应为 "answer1"

我试试:

var e = _.find(db, function(o){
    o.words === "say"
});
console.log(e);

但是我找不到结果;

显然,我没有定义,因为我正在比较一个精确的值。如何获取值?

嗯,你也得到 undefined 因为你也没有返回 o.words === "say" 比较。

但你是对的,这种比较在这种情况下不起作用。您应该在 _.find 回调中使用类似 _.some 的内容:

var e = _.find(db, function(o) {
    return _.some(o.words, function(word) {
        return word === 'say';
    });
});

这应该给你返回对象(或者未定义,如果找到 none)。如果你想要 answer 具体来说,你仍然需要将它从对象中拉出来。

这是 working fiddle。请注意,您还应该对 undefined 对象/属性进行一些额外的保护。不过,我会把它留给你。

ES6 版本:

const term = "word1b";

const res = _(db)
  .filter(item => item.words.indexOf(term) !== -1)
  .first()
  .answer;

正如另一个答案中提到的,您仍然应该检查是否存在预先从返回的对象中获取 .answer 值。

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