【问题标题】:Find a value in an array inside other array with lodash使用 lodash 在其他数组内的数组中查找一个值
【发布时间】:2016-07-24 17:48:39
【问题描述】:

我有一个数组,例如:

var db = [{
        "words": ["word1a", "word1b", "word1c"],
        "answer": "answer1"
    }, {
        "words": ["word2a", "words2b"],
        "answer": "answer2"
    }]

我在 node.js 上使用 lodash 来检查数组中的值。我想搜索单词并返回响应。例如,如果我搜索“word1a”,则响应为“answer1”

我试试:

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

但是我找不到结果;

显然,我得到了未定义,因为我正在比较一个确切的值。如何获得价值?

【问题讨论】:

    标签: arrays node.js lodash


    【解决方案1】:

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

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

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

    这应该会返回对象(或未定义,如果没有找到)。如果你特别想要answer,你仍然需要把它从对象中拉出来。

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

    【讨论】:

      【解决方案2】:

      一个 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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-10
        • 1970-01-01
        • 2022-01-21
        • 2021-10-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多