2

我有一个看起来像这样的数组。

Users : {
  0 : { BidderBadge: "somestuff", Bidders: 6, }
  1 : { BidderBadge: "somemorestuff", Bidders: 7,}
}

我想使用 lodash 搜索数组以在每个用户对象中找到一个值。

具体来说,我想使用另一个类似对象数组中的值来查找值。

var bidArray = [];
    _.each(this.vue.AllUsers, function(user) {
      _.each(this.vue.Bids, function(bid) {
        if(user.BidderBadge == bid.Badge) {   
          bidArray.push(user);
        }
      });
    });

这就是我所拥有的并且它有效,但我想只使用一个循环而不是两个循环来做到这一点。我想使用 _.indexOf 之类的东西。那可能吗?

4

2 回答 2

3

如果你想避免嵌套,你只需要稍微修改一下 Azamantes 的解决方案

var bidders = this.vue.Bids.reduce(function(acc, bid) {
    return acc[bid.BidderBadge] = true;
}, {});
var bidArray = this.vue.AllBidders.filter(function(bidder) {
    return !!bidders[bidder.Badge];
});
于 2016-10-12T17:03:28.053 回答
1

很难通过与您提供的输入不一致的示例给出准确的答案。

无论如何,假设您的数据结构或多或少像这样,您可以使用 lodash _.intersectionWith解决问题。

使用检查正确对象属性的比较器将两个数组相交。此外,请考虑到用户必须先进入交叉路口,因为您对其值感兴趣。

function comparator(user, bid) {
  return user.BidderBadge === bid.Badge;
}
console.log(_.intersectionWith(users, bids, comparator));

这是小提琴

于 2016-10-12T17:36:11.347 回答