javascript - 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
}
}
}
我操作的真实数据嵌套任意深(通常是几十个对象内的对象),但我希望上面的示例有所帮助。
这是一项一次性的任务,所以我并不特别关心性能,只要它有效,我很乐意使用任何库。谢谢您的帮助!
解决方案
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; }
推荐阅读
- android - OsmDroid:由于 mWriter 为空,TileLoader 无法加载图块(地图关闭?)
- python - 从具有两种不同功能的列表中生成所有可能的结果
- python - Django 如何返回 object.filter 查询结果,所以我不必遍历它们
- javascript - React Router 无法与 Exact 和 Switch 一起正常工作
- browser-sync - BrowserSync 的问题
- c# - 使用 C# 互操作从 Powerpoint 笔记中删除超链接?
- java - 未调用 log4j 自定义附加程序停止方法
- apache-calcite - LogicalCorrelate 和 LogicalJoin 有什么不同?
- .htaccess - 使用 .htaccess 重定向到 https、子文件夹并防止裸域 URL?
- c++ - 在 MsSQL Server 查询中使用 C++ 变量但变量不起作用