You need to enable JavaScript to run this app. 如何比较两个JSON对象并返回二者共有的匹配属性与对应值
优惠活动
大模型
产品
解决方案
定价
更多

如何比较两个JSON对象并返回二者共有的匹配属性与对应值

实现方案

注:你给出的parentUser中"game": {"edit"}存在语法错误,我默认修正为"game": {"edit": true}进行演示。

我们可以通过递归深度遍历两个对象,仅保留两侧同时存在、类型一致、值全等的属性结构,代码实现如下:

function getMatchingProperties(objA, objB) {
  // 类型不同直接过滤
  if (typeof objA !== typeof objB) return undefined;

  // 处理基本类型对比
  if (typeof objA !== 'object' || objA === null || objB === null) {
    return objA === objB ? objA : undefined;
  }

  // 数组对比逻辑(如果确定没有数组场景可删除这部分)
  if (Array.isArray(objA) && Array.isArray(objB)) {
    const res = [];
    const minLen = Math.min(objA.length, objB.length);
    for (let i = 0; i < minLen; i++) {
      const match = getMatchingProperties(objA[i], objB[i]);
      if (match !== undefined) res.push(match);
    }
    return res.length ? res : undefined;
  }

  // 普通对象对比逻辑
  const res = {};
  // 取两个对象的公共属性键
  const commonKeys = Object.keys(objA).filter(key => Object.prototype.hasOwnProperty.call(objB, key));
  for (const key of commonKeys) {
    const matchVal = getMatchingProperties(objA[key], objB[key]);
    if (matchVal !== undefined) {
      res[key] = matchVal;
    }
  }
  // 空对象直接过滤不返回
  return Object.keys(res).length ? res : undefined;
}

// 测试用例
const currentUser = {"subAccount":{"setup":true, "edit": true, "delete": true}};
const parentUser = {"subAccount":{"setup":true, "edit": true}, "game": {"edit": true}};

const result = getMatchingProperties(currentUser, parentUser);
console.log(JSON.stringify(result, null, 2));

运行后输出结果和你预期完全一致:

{
  "subAccount": {
    "setup": true,
    "edit": true
  }
}

逻辑说明

  • 优先校验对比值的类型,类型不同直接过滤
  • 递归处理嵌套结构,只有递归返回有效值时才保留对应属性
  • 自动过滤仅在单侧存在的属性、以及值不相等的属性
  • 兼容基本类型、普通对象、数组三类常用结构,可根据自己的业务场景裁剪不需要的分支

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 19:24:05