如何在键名动态未知的对象数组中查找匹配对象?
检查动态键对象是否存在于对象数组中
我有如下对象数组:
[ {"firstKey":"firstValue","secondKey":"secondValue"}, {"thirdKey":"thirdValue","forthKey":"forthValue"} ]以及如下对象:
{"thirdKey":"thirdValue","forthKey":"forthValue"}需要检查该对象是否存在于上述对象数组中,注意:对象的键是动态生成的,我并不知晓键的名称。
方案一:用JSON.stringify快速判断(适合键顺序固定的场景)
直接把数组里的每个对象和目标对象转成JSON字符串,对比是否完全一致:
const objArray = [ {"firstKey":"firstValue","secondKey":"secondValue"}, {"thirdKey":"thirdValue","forthKey":"forthValue"} ]; const targetObj = {"thirdKey":"thirdValue","forthKey":"forthValue"}; const isExists = objArray.some(item => JSON.stringify(item) === JSON.stringify(targetObj)); console.log(isExists); // 输出 true
提醒:如果对象的键顺序可能不一样(比如目标对象是{forthKey:"forthValue", thirdKey:"thirdValue"}),这种方法会失效,因为字符串化后的顺序不同。
方案二:深度对比对象(更严谨,支持键顺序不一致的情况)
写个辅助函数,先对比两个对象的键数量,再逐个检查键和对应的值是否完全匹配,再用Array.some遍历数组:
// 辅助函数:判断两个对象是否完全相等 function checkObjectMatch(obj1, obj2) { // 先排除非对象或null的情况 if (typeof obj1 !== 'object' || obj1 === null || typeof obj2 !== 'object' || obj2 === null) { return obj1 === obj2; } const keys1 = Object.keys(obj1); const keys2 = Object.keys(obj2); // 键数量不同直接不匹配 if (keys1.length !== keys2.length) return false; // 遍历每个键,检查是否存在且值相等 for (const key of keys1) { if (!keys2.includes(key) || !checkObjectMatch(obj1[key], obj2[key])) { return false; } } return true; } // 执行检查 const objArray = [ {"firstKey":"firstValue","secondKey":"secondValue"}, {"thirdKey":"thirdValue","forthKey":"forthValue"} ]; const targetObj = {"thirdKey":"thirdValue","forthKey":"forthValue"}; const isExists = objArray.some(item => checkObjectMatch(item, targetObj)); console.log(isExists); // 输出 true
这个方法还支持嵌套对象的对比,不管键的顺序如何,只要键值对完全一致就会判定为匹配。
内容的提问来源于stack exchange,提问作者paranoid
相关产品推荐
相关产品推荐

