【问题标题】:Filter objects based on a match in another array根据另一个数组中的匹配过滤对象
【发布时间】:2017-07-25 21:52:47
【问题描述】:

我正在尝试使用 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 显示码。

【问题讨论】:

    标签: javascript lodash


    【解决方案1】:

    很难理解你的意思,院子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
    

    【讨论】:

    • 抱歉,我想过滤 this.yards 以仅显示球队可以访问的码数,因此来自球队 -> 码 -> yard.id 的匹配将在 yard.id 中匹配这个.码。希望这更有意义。
    【解决方案2】:

    由于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>

    所以这会返回与至少一支球队相关的码数。

    【讨论】:

    • 嗨,抱歉,我应该更清楚一点,我已经从团队数据中选择了一个“团队”: var team = _.find(this.teams, { 'id': this.newSchedule 。团队});已更新我的问题。
    • 在这种情况下,您的问题仍然令人困惑,因为它仍然将 team 显示为数组。其次,您拥有的代码似乎可以正常工作(请参阅jsfiddle.net/4yocg6wj,尽管在您的情况下无法猜测this 是什么),所以还有另一个问题。请提供足够的代码让我们能够重现该问题。同时提供所需的输出。
    猜你喜欢
    • 2019-09-15
    • 2020-08-15
    • 2019-09-30
    • 2019-04-05
    • 2021-10-24
    • 2022-11-30
    • 2022-11-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多