首页 > 解决方案 > JavaScript 中两个深层对象的交集

问题描述

我有两个具有许多相同信息的 JavaScript 对象(任意深度)。

我正在寻求帮助来获取两个对象之间的共享数据

例如:

const a = {
  name: 'Alice',
  features: {
    speed: 3,
    strength: 90,
    mind: {
      power: 42
    }
  }
};

const b = {
  name: 'Bob',
  features: {
    speed: 3,
    stamina: 1,
    mind: {
      power: 42,
      flexibility: 0,
      telekinesis: 42
    }
  }
};

我的目标是提出一个解决方案来生成他们共享的数据:

const shared = {
  features: {
    speed: 3,
    mind: {
      power: 42
    }
  }
}

我操作的真实数据嵌套任意深(通常是几十个对象内的对象),但我希望上面的示例有所帮助。

这是一项一次性的任务,所以我并不特别关心性能,只要它有效,我很乐意使用任何库。谢谢您的帮助!

标签: javascriptobjectnestedjavascript-objects

解决方案


You could use an recursve approach by checking the existence of properties in both objects, truthy properties and same object type or same values.

The use of a variable temp prevents empty nested objects.

function common(object1, object2) {
    return Object.assign(...Object.keys(object1).map(k => {
        var temp;
        if (!(k in object2)) {
            return {};
        }
        if (object1[k] && typeof object1[k] === 'object' &&
            object2[k] && typeof object2[k] === 'object') {
            temp = common(object1[k], object2[k]);
            return Object.keys(temp).length ? { [k]: temp } : {};
        }
        if (object1[k] === object2[k]) {
           return { [k]: object1[k] };
        }
        return {};
    }));
}

const
    a = { name: 'Alice', features: { speed: 3, strength: 90, mind: { power: 42 } } };
    b = { name: 'Bob', features: { speed: 3, stamina: 1, mind: { power: 42, flexibility: 0, telekinesis: 42 } } };

console.log(common(a, b));
.as-console-wrapper { max-height: 100% !important; top: 0; }


推荐阅读