根据另一个数组中的匹配过滤对象

时间:2017-07-25 21:52:47

标签: javascript lodash

我正在尝试使用Lodash根据id的匹配过滤一系列对象,这就是我尝试过的:

var team = _.find(this.teams, { 'id': this.newSchedule.team});
_.filter(this.yards, function(yard) {
    return _.find(team.yards, { id: yard.id });
});

码数据:

[ { "id": 1, "name": "Test" },{ "id": 2, "name": "Test 2" } ]

团队数据:

[ { "id": 1, "name": "Team 1", "yards": [{ "id": 1, "name" }] ]

我希望this.yards根据所选团队的码ID来显示码数。

2 个答案:

答案 0 :(得分:0)

很难理解你的意思,院子id是否与团队id匹配?

如果是这样的话,你需要做的就是首先找到具有相同id的团队,然后抓住那些团队码。因此我会使用map函数两次:

const result = this
  .yards
  .map(y => team.find(t => t.id === y.id)) // join with the right team
  .map(t => t.yards)                       // reduce to that teams yards

答案 1 :(得分:0)

由于team是一个数组,因此需要在对该数组中的单个元素执行_.find之前对其进行迭代。调用变量team(单数)并没有用。 teams会更有意义。

以下是更改lodash代码的方法:

var yards = [ { id: 1, name: "Test" },{ id: 2, name: "Test 2" } ],
    teams = [ { id: 1, name: "Team 1", yards: [{ id: 1, name: "Missing string" }] } ]

    result = _.filter(this.yards, function(yard) {
      return _.some(this.teams, function(team) {
        return _.find(team.yards, { id: yard.id });
      });
    });

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js"></script>

因此,这将返回与至少一个团队相关的码数。

相关问题