【问题标题】:JavaScript filter through array and only return based on match of one valueJavaScript 通过数组过滤并仅基于一个值的匹配返回
【发布时间】:2018-08-06 05:08:30
【问题描述】:

我有一个对象数组,它们都有一个阶段键,我只想返回与特定阶段值匹配的对象,然后将其他几个键/值映射到最终返回中。这是我目前所拥有的:

phaseToBlocks (toggle, phase) {
  this.phaseBlocks = this.$store.state.addresses.salesRepPhases
  return this.phaseBlocks
    .filter(fiber_phase === phase)
    // .map(({id, phase, name, min_number, max_number}) => ({id: id, phase: fiber_phase, name: name, min_number: min_number, max_number: max_number}))
}

这目前没有过滤掉任何对象并返回原始对象数组。这是对象数组的 sn-p:

[ { "fiber_phase": "101", "parsed_hash": "1bc7fb114ee10d7cb9cea10693d238b5", "min_number": 400, "max_number": 499, "sales_rep": "164", "id": "abd90d6b-28a8-2be6-d6c1-abd9007aef38", "name": "48TH ST E", "block_minimum": 400, "block_maximum": 498 }, { "fiber_phase": "101", "parsed_hash": "1bc7fb114ee10d7cb9cea10693d238b5", "min_number": 400, "max_number": 499, "sales_rep": "164", "id": "abd90d6b-28a8-2be6-d6c1-abd9007aef38", "name": "48TH ST E", "block_minimum": 401, "block_maximum": 499 }, { "fiber_phase": "103", "parsed_hash": "1e002ef82be950696f9053dc77b621cf", "min_number": 4700, "max_number": 4799, "sales_rep": "164", "id": "a1d58c9c-6ba7-ebc6-8a74-a1d5806e0bcf", "name": "11TH AVE S", "block_minimum": 4700, "block_maximum": 4798 }]

【问题讨论】:

  • filter(p => p.phase === phase) 假设 phaseBlocks 有一个 phase 属性。
  • 密钥其实是fiber_phase。那么它会是filter(p => p.fiber_phase === phase)?
  • 是的,如果那是应该等于 phase 的属性。
  • 嗯,还是不行。我需要先映射对象数组吗?像这样:return this.phaseBlocks .map(({id, fiber_phase, name, min_number, max_number}) => ({id: id, phase: fiber_phase, name: name, min_number: min_number, max_number: max_number})) .filter(p => p.fiber_phase === phase)
  • 有可能phase 是数字而fiber_phase 不是,这会导致=== 失败。

标签: javascript arrays filter vue.js ecmascript-6


【解决方案1】:

filter() 接受一个回调函数来检查条件并进行过滤:

return this.phaseBlocks
    .filter(item => item.phase === phase);

【讨论】:

    【解决方案2】:

    如果您不清楚 .filter 的工作原理,请参阅:

    this.phaseBlocks.filter((phaseBlock) => {
       return phaseBlock.fiber_phase === phase;
    });
    

    filter 遍历数组,(phaseBlock) 是当前被迭代的数组元素。

    接下来,如果项目满足条件(在这种情况下,它的fiber_phase 属性等于phase)将该项目推送到由filter 创建的新数组中。

    有关更多信息,请查看文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-29
      • 1970-01-01
      • 2021-11-21
      • 2019-11-02
      • 1970-01-01
      • 1970-01-01
      • 2021-08-12
      • 2021-10-08
      相关资源
      最近更新 更多