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

JavaScript数组条件过滤:校验指定键值全为true并筛选结果

问题描述

我有两个数组,第一个数组存储若干键名,需要校验第二个数组中的对象是否满足所有指定键对应的值均为true,最终返回符合条件的对象数组。

现有代码示例:

const keysArray = ['phoneNo', 'name']

const data = [
  { demo1:'abc', match_status:{ phoneNo: true, name: null }}, 
  { demo2:'abc', match_status_flag:{ phoneNo: true, name: true }}
]

预期输出:

const outputArray = [{ demo2:'abc', match_status_flag:{ phoneNo: true, name: true }}]

我尝试了以下代码,但未得到预期结果:

keysArray.map((k) => data.filter(i => i.match_status[k] === true))
问题分析与解决代码

你的代码存在两个核心问题:

  1. 使用keysArray.map()会对每个键单独过滤数据,最终返回二维数组,而非预期的一维结果数组。
  2. 固定读取match_status字段,但示例数据中第二个对象的状态字段是match_status_flag,导致无法匹配到目标数据。

以下是正确的实现代码:

const keysArray = ['phoneNo', 'name']

const data = [
  { demo1:'abc', match_status:{ phoneNo: true, name: null }}, 
  { demo2:'abc', match_status_flag:{ phoneNo: true, name: true }}
]

const outputArray = data.filter(item => {
  // 找到当前对象中包含所有指定键的嵌套状态对象
  const statusObj = Object.values(item).find(val => 
    typeof val === 'object' && val !== null && keysArray.every(key => key in val)
  );
  // 校验所有指定键的值是否都为true
  return statusObj && keysArray.every(key => statusObj[key] === true);
});

console.log(outputArray);
// 输出:[{ demo2:'abc', match_status_flag:{ phoneNo: true, name: true }}]

代码说明:

  • data.filter():遍历数据数组,只保留符合条件的对象。
  • Object.values(item).find(...):自动识别当前对象中包含所有目标键的嵌套对象,无需固定字段名。
  • keysArray.every(key => statusObj[key] === true):确保所有指定键对应的值严格等于true。

如果你的业务场景中,状态字段的键名是固定的(比如统一为match_status),可以简化代码为:

const outputArray = data.filter(item => 
  keysArray.every(key => item.match_status?.[key] === true)
);

内容的提问来源于stack exchange,提问作者rahul5140

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 05:10:23