基于NOT关键字过滤对象数组并提取有效ID的实现需求
实现带正向/反向规则的数据过滤逻辑
首先给出你的过滤规则和原始数据:
过滤规则
const array = [ { DEVICE_SIZE: ['036', '048', '060', '070'] }, { DEVICE_VOLTAGE: ['1', '3'] }, { 'NOT DEVICE_DISCHARGE_AIR': ['S'] }, { 'NOT DEVICE_REFRIGERANT_CIRCUIT': ['H', 'C'] }, ];
原始数据
const data = { DEVICE_SIZE: [ { id: 20, name: 'Size 20' }, { id: 36, name: 'Size 36' }, { id: 40, name: 'Size 40' }, { id: 48, name: 'Size 48' }, // 修正原数据笔误:原id为20,应为48才能匹配规则 { id: 60, name: 'Size 60' }, { id: 70, name: 'Size 70' }, ], DEVICE_VOLTAGE: [ { id: 1, name: 'Voltage 1' }, { id: 2, name: 'Voltage 2' }, { id: 3, name: 'Voltage 3' }, { id: 4, name: 'Voltage 4' }, { id: 5, name: 'Voltage 5' }, ], DEVICE_DISCHARGE_AIR: [ { id: 'E', name: 'Discharge E' }, { id: 'S', name: 'Discharge S' }, { id: 'T', name: 'Discharge T' }, ], DEVICE_REFRIGERANT_CIRCUIT: [ { id: 'C', name: 'Refrigerant C' }, { id: 'E', name: 'Refrigerant E' }, { id: 'H', name: 'Refrigerant H' }, { id: 'M', name: 'Refrigerant M' }, ], };
实现代码
直接遍历规则数组,区分正向/反向匹配,处理类型统一和键名映射:
const valid = {}; array.forEach(rule => { // 提取当前规则的键和值列表 const [ruleKey, ruleValues] = Object.entries(rule)[0]; // 判断是否为反向规则,获取对应的数据键名 const isReverse = ruleKey.startsWith('NOT '); const dataKey = isReverse ? ruleKey.slice(4) : ruleKey; // 统一规则值的类型:将带前导零的字符串转为数字,避免类型不匹配 const normalizedRules = ruleValues.map(val => { const num = Number(val); return isNaN(num) ? val : num; }); // 过滤出符合条件的ID const filteredIds = data[dataKey] .map(item => item.id) .filter(id => isReverse ? !normalizedRules.includes(id) : normalizedRules.includes(id)); // 处理输出键名(匹配你期望的DEVICE_DISCHARGE) let outputKey = dataKey; if (outputKey === 'DEVICE_DISCHARGE_AIR') { outputKey = 'DEVICE_DISCHARGE'; } valid[outputKey] = filteredIds; }); console.log(valid);
输出结果
运行后会得到你期望的有效ID对象:
const valid = { DEVICE_SIZE: [36, 48, 60, 70], DEVICE_VOLTAGE: [1, 3], DEVICE_DISCHARGE: ["E", "T"], DEVICE_REFRIGERANT_CIRCUIT: ["E", "M"], };
内容的提问来源于stack exchange,提问作者Hello World
相关产品推荐
相关产品推荐

