[英]Check if matching keys are equal
I searched if this question is present here, but can't find it.我搜索了这里是否存在这个问题,但找不到。
Say we have two objects and we want to check if the matching keys are equal, for example:假设我们有两个对象,我们想检查匹配的键是否相等,例如:
const style1 = {
color: 'brown',
backgroundColor: 'blue',
border: '3px solid blue'
}
const style2 = {
fontSize: '16px',
padding: '10px',
color: 'brown'
}
The result of something like:类似的结果:
isMatchingKeysEqual(style1, style2)
should return true
应该返回true
Iterate over the key / value pairs ( "entries" ) of one object and check if any match the other via Array.prototype.some()
.迭代一个对象的键/值对( “entries” ),并通过Array.prototype.some()
检查是否有匹配另一个。
function isMatchingKeysEqual(obj1, obj2) { return Object.entries(obj1).some(([ key, val ]) => obj2[key] === val) } const style1 = { color: 'brown', backgroundColor: 'blue', border: '3px solid blue' } const style2 = { fontSize: '16px', padding: '10px', color: 'brown' } console.log(isMatchingKeysEqual(style1, style2))
Note, this only works on an object with a depth of 1. If you needed to check complex objects with object or array values, you'd need to do something recursive.请注意,这仅适用于深度为 1 的对象。如果您需要检查具有对象或数组值的复杂对象,则需要执行一些递归操作。
I have been thinking about this problem for several days, and I believe I have a satisfactory solution.这个问题我想了好几天了,相信我已经有了一个满意的解决方案。
I wanted to write a function that could take in n number of object arguments.我想编写一个可以接收 n 个对象参数的函数。 So that it could be used for more than just two objects.这样它就可以用于不止两个对象。
Here it is:这里是:
function areIntersectingKeysEqual(...objects) {
return objects
.map((object) => Object.keys(object))
.sort((a, b) => a.length - b.length)
.reduce((a, b) => a.filter((key) => b.includes(key)))
.every((key) => objects.every((object) => object[key] === objects[0][key]));
}
Let me explain how it works.让我解释一下它是如何工作的。
At a high level, first we find the intersecting keys, then we determine if all intersecting keys are equal.在高层次上,首先我们找到相交的键,然后我们确定是否所有相交的键都相等。
Here is how it is used.这是它的使用方法。
function areIntersectingKeysEqual(...objects) { return objects .map((object) => Object.keys(object)) .sort((a, b) => a.length - b.length) .reduce((a, b) => a.filter((key) => b.includes(key))) .every((key) => objects.every((object) => object[key] === objects[0][key])); } const style1 = { color: 'brown', backgroundColor: 'blue', border: '3px solid blue', }; const style2 = { fontSize: '16px', padding: '10px', color: 'brown', }; const style3 = { fontSize: '10px', color: 'blue', }; areIntersectingKeysEqual(style1, style2); // true areIntersectingKeysEqual(style1, style2, style3); // false
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.