JavaScript通过数组进行过滤,并仅基于一个值的匹配返回
我有一个对象数组,所有对象都有一个相位键,我只想返回与特定相位值匹配的对象,然后将其他几个键/值映射到最终的返回中。以下是我目前掌握的情况:JavaScript通过数组进行过滤,并仅基于一个值的匹配返回,javascript,arrays,filter,vue.js,ecmascript-6,Javascript,Arrays,Filter,Vue.js,Ecmascript 6,我有一个对象数组,所有对象都有一个相位键,我只想返回与特定相位值匹配的对象,然后将其他几个键/值映射到最终的返回中。以下是我目前掌握的情况: phaseToBlocks (toggle, phase) { this.phaseBlocks = this.$store.state.addresses.salesRepPhases return this.phaseBlocks .filter(fiber_phase === phase) // .map(({id, phas
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}))
}
这目前没有过滤出任何对象并返回原始对象数组。以下是对象数组的一个片段:
[ { "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()
接受一个回调函数,该函数检查条件并执行过滤:
return this.phaseBlocks
.filter(item => item.phase === phase);
filter()
接受一个回调函数,该函数检查条件并执行过滤:
return this.phaseBlocks
.filter(item => item.phase === phase);
如果您不清楚
.filter
的工作原理,请参阅以下内容:
this.phaseBlocks.filter((phaseBlock) => {
return phaseBlock.fiber_phase === phase;
});
filter
迭代数组,而(phaseBlock)
是当前迭代的数组元素
接下来,如果项目满足条件(在这种情况下,其光纤相位
属性等于相位
),则将该项目推送到由过滤器
创建的新数组中
有关更多信息,请查看文档:如果您不清楚
.filter
的工作原理,请参阅以下内容:
this.phaseBlocks.filter((phaseBlock) => {
return phaseBlock.fiber_phase === phase;
});
filter
迭代数组,而(phaseBlock)
是当前迭代的数组元素
接下来,如果项目满足条件(在这种情况下,其光纤相位
属性等于相位
),则将该项目推送到由过滤器
创建的新数组中
更多信息,请查看文档:
过滤器(p=>p.phase===phase)
假设phaseBlocks
具有phase
属性。键实际上是fiber\u phase
。那么它就是过滤器(p=>p.fiber\u phase===phase)
?是的,如果这个属性应该等于phase
.Hmm,仍然不起作用。我需要先映射对象数组吗?这样:返回this.phaseBlocks.map({id,fiber\u phase,name,min\u number,max\u number})=>({id:id,phase:fiber\u phase,name:name,min\u number:min\u number,max\u number})).filter(p=>p.fiber\u phase====phase)
假设phaseblock
具有phase
属性,则可能===
是数值而fiber\u phase
不是数值,这将导致==
失败。filter(p=>p.phase===phase)
假设phaseblock
具有phase
属性。键实际上是fiber\u phase。那么它就是过滤器(p=>p.fiber\u phase===phase)
?是的,如果这个属性应该等于phase
.Hmm,仍然不起作用。我需要先映射对象数组吗?这样:返回this.phaseBlocks.map({id,fiber\u phase,name,min\u number,max\u number})=>({id:id,phase:fiber\u phase,name:name,min\u number:min\u number,max\u number})).filter(p=>p.fiber\u phase===phase)
可能phase
是数字而fiber\u phase
不是数字,这将导致=
失败。