基于多筛选值过滤对象:从some到every的需求变更
Got it, let's walk through how to solve this. You need to filter your testObject array so that only items that meet all the conditions in filterObject are kept, then extract their IDs. Here's a clean implementation using every() alongside some() for the per-dimension checks:
Step-by-Step Explanation
First, let's clarify the requirements for each item to pass the filter:
- The item's
location_taxarray must share at least one value withfilterObject.locations - The item's
roundTypearray must share at least one value withfilterObject.roundTypes - The item's
vertical_taxarray must share at least one value withfilterObject.verticals
We'll use some() to check for overlap in each dimension, then wrap those checks in every() to ensure all three conditions are satisfied.
Code Implementation
// Your input data const testObject = [ { "id": 1892928, "vertical_tax": [ 678, 664 ], "location_tax": [ 666 ], "roundType": [ "rt1" ] }, { "id": 1892927, "vertical_tax": [ 662, 663 ], "location_tax": [ 663 ], "roundType": [ "rt2" ] } ]; // Your filter criteria const filterObject = { locations: [666,667], roundTypes: ["rt1","rt2"], verticals: [662,661] }; // Filter and extract matching IDs const matchedIds = testObject .filter(item => { // Check if location matches (any overlap between item's location_tax and filter locations) const hasMatchingLocation = item.location_tax.some(loc => filterObject.locations.includes(loc)); // Check round type match const hasMatchingRoundType = item.roundType.some(rt => filterObject.roundTypes.includes(rt)); // Check vertical match const hasMatchingVertical = item.vertical_tax.some(vt => filterObject.verticals.includes(vt)); // Use every() to ensure ALL three conditions are true return [hasMatchingLocation, hasMatchingRoundType, hasMatchingVertical].every(condition => condition); }) .map(item => item.id); // Extract just the IDs from matching objects console.log(matchedIds); // Output: [] (neither item meets all three criteria in your example)
Notes on Edge Cases
If you want to handle empty filter arrays (e.g., if filterObject.locations is empty, that condition should automatically pass), you can adjust each check like this:
const hasMatchingLocation = filterObject.locations.length === 0 ? true : item.location_tax.some(loc => filterObject.locations.includes(loc));
Repeat this pattern for the round type and vertical checks to make the filter more flexible.
内容的提问来源于stack exchange,提问作者Kavya nagendra

