简体   繁体   中英

JavaScript filter through array and only return based on match of one value

I have an array of objects that all have a phase key and I would like to only return the ones that match a specific phase value and then map several other key/values into the eventual return. Here's what I have so far:

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}))
}

This is currently not filtering any out and returning the original array of objects. Here is a snippet of the array of objects:

[ { "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() takes a callback function that checks the condition and does the filtering:

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

If it's not clearer for you how .filter works, see this:

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

filter iterates through the array, and (phaseBlock) is the element of the array that is currently iterated.

Next, if the item is satisfying a condition (in this case its fiber_phase property is equal to phase ) push that item to a new array created by filter .

For more, check the docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM