如何通过键值在JavaScript对象数组中查找目标对象?
如何在对象数组中深度匹配查找目标对象
要实现你需要的功能,核心是深度校验对象是否包含目标的所有键值对,再遍历数组找到第一个匹配项。你用for in失败大概率是没处理嵌套对象,或者误用for in遍历数组(for in适合遍历对象键,遍历数组更推荐for...of或普通for循环)。
实现代码
首先写一个递归的匹配辅助函数,用来判断源对象是否深度包含目标对象的所有键值:
function matches(source, target) { for (const key in target) { // 处理嵌套对象,排除null(typeof null === 'object') if (typeof target[key] === 'object' && target[key] !== null) { if (!source.hasOwnProperty(key) || !matches(source[key], target[key])) { return false; } } else { // 非对象值直接比较 if (source[key] !== target[key]) { return false; } } } return true; }
然后实现查找函数,自动区分输入的数组项和目标对象:
function findObject(...args) { const target = args.pop(); const objArray = args; // 遍历数组找第一个匹配项 for (const obj of objArray) { if (matches(obj, target)) { return obj; } } return undefined; }
测试你的示例
const result = findObject( { a: 1, b: { c: 2 } }, { a: 1, b: { c: 3 } }, { c: 3 }, { c: 3 } // 目标对象 ); console.log(result); // 输出:{ a: 1, b: { c: 3 } }
关键说明
- 嵌套匹配:
matches函数会递归遍历目标对象的所有嵌套层级,确保每个键值对都在源对象中存在且匹配; - 数组遍历:用
for...of遍历数组,避免for in遍历数组时会读取原型链属性的问题; - 边界处理:自动跳过null值的判断,支持任意层级的嵌套对象结构。
内容的提问来源于stack exchange,提问作者Unreal
相关产品推荐
相关产品推荐

