You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:39:08