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

如何检查对象数组中是否包含指定变量值(附示例代码)

检查对象数组中是否包含指定值的方法

针对你给出的代码场景,这里提供几种直接的实现方式:

基础判断:是否存在目标值

使用数组的some()方法,它会在找到第一个符合条件的元素后立即停止遍历,效率较高:

function weatherCodes(){
  let codes = [{sunny:[1001]},{cloudy:[1002,1003]}]
  let theCode = 1003;
  
  const exists = codes.some(item => {
    // 取出每个对象里的数组值(每个对象仅含一个键值对)
    const codeList = Object.values(item)[0];
    return codeList.includes(theCode);
  });
  
  console.log(exists); // 输出 true
};

weatherCodes();

扩展场景:对象可能含多个键值对

如果数组中的对象可能有多个数组类型的属性,可以调整为遍历对象的所有值数组:

const exists = codes.some(item => {
  return Object.values(item).some(arr => arr.includes(theCode));
});

进阶:找到包含目标值的具体元素

如果需要定位到具体是哪个对象包含目标值,用find()方法:

function weatherCodes(){
  let codes = [{sunny:[1001]},{cloudy:[1002,1003]}]
  let theCode = 1003;
  
  const targetItem = codes.find(item => {
    return Object.values(item).some(arr => arr.includes(theCode));
  });
  
  console.log(targetItem); // 输出 {cloudy: [1002, 1003]}
};

weatherCodes();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 19:48:13