如何检查键值对对象数组中是否存在指定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
相关产品推荐
相关产品推荐

