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

如何检查键值对对象数组中是否存在指定Key

问题说明

现有如下结构的数组:

[
   {Key: 'FName', Value: 'John'},
   {Key: 'LName', Value: 'Doe'},
   {Key: 'Age', Value: '30'},
   {Key: 'Person', Value: 'true'}
]

需要判断Person是否作为元素的Key属性值存在于上述数组中。

实现方案

优先使用数组原生的some()方法实现,该方法在遍历到第一个符合条件的元素时就会终止遍历并返回true,所有元素都不符合条件时返回false,性能最优。

const dataList = [
   {Key: 'FName', Value: 'John'},
   {Key: 'LName', Value: 'Doe'},
   {Key: 'Age', Value: '30'},
   {Key: 'Person', Value: 'true'}
]

const isPersonExist = dataList.some(item => item.Key === 'Person')
console.log(isPersonExist) // 匹配到对应项,输出true

如果需要兼容不支持some()的极老旧运行环境,可以用基础for循环实现同等逻辑:

function checkKeyExist(list, targetKey) {
  for (let i = 0; i < list.length; i++) {
    if (list[i].Key === targetKey) {
      return true
    }
  }
  return false
}

// 调用示例
const isPersonExist = checkKeyExist(dataList, 'Person')

注意:不建议使用map、forEach这类会完整遍历整个数组的方法做存在性判断,数据量较大时会产生无意义的性能损耗。

内容的提问来源于stack exchange,提问作者Pa3k.m

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 10:36:16