JavaScript单/多字段数据过滤功能实现需求咨询
Got it, let's tackle this JavaScript filtering problem you're working on. Here's a flexible approach that handles both single-field and multi-field filtering nicely:
First, let's recap your sample data for reference:
const arr = [ { "t_id" : "abc", "s_id" : "pai" }, { "t_id" : "pai", "s_id" : "par" }, { "t_id" : "pai", "s_id" : "pas" }, { "t_id" : "pai", "s_id" : "pai" }, { "t_id" : "par", "s_id" : "pas" } ];
Single Field Filtering
For your specific case of filtering all items where t_id equals 'pai', JavaScript's built-in Array.filter() method is perfect—it's straightforward and readable:
// Filter items where t_id is exactly 'pai' const filteredByTId = arr.filter(item => item.t_id === 'pai'); console.log(filteredByTId);
This will return exactly the set of objects you need:
[ { "t_id": "pai", "s_id": "par" }, { "t_id": "pai", "s_id": "pas" }, { "t_id": "pai", "s_id": "pai" } ]
Multi Field Filtering
If you need to filter by multiple fields later (like both t_id and s_id), a reusable function makes more sense. This way you don't have to rewrite filter logic every time:
// Generic function to filter by any number of field-value pairs function filterByFields(data, filterConditions) { return data.filter(item => { // Make sure every key in the filter conditions matches the item's value return Object.keys(filterConditions).every(key => { return item[key] === filterConditions[key]; }); }); } // Example: Filter items where t_id is 'pai' AND s_id is 'pas' const multiFiltered = filterByFields(arr, { t_id: 'pai', s_id: 'pas' }); console.log(multiFiltered);
The output here would be:
[ { "t_id": "pai", "s_id": "pas" } ]
Bonus: Extending for Non-Exact Matches
If you ever need fuzzy matching (like checking if a field contains a substring instead of exact equality), you can tweak the condition inside the every() method. For example:
// Check if the item's field contains the filter value (case-insensitive) return item[key].toLowerCase().includes(filterConditions[key].toLowerCase());
内容的提问来源于stack exchange,提问作者Nitin

