我想比较两个 json 对象,不包括其中一个键
我有两个对象 x,y,我想比较这两个对象,不包括其中一个键“c”
let x = {a: 5, b: 6, c: "string"}
let y = {a: 5, b: 8, c: "string"}
我想如何比较它 -
JSON.stringify(x) === JSON.stringify(y)
上面的工作原理,但它会比较我想在此处比较时排除 c 的所有键。实现这一目标的最佳方法是什么?
I have two objects x,y and i want to compare both of these excluding one of the keys "c"
let x = {a: 5, b: 6, c: "string"}
let y = {a: 5, b: 8, c: "string"}
How i am trying to compare it is -
JSON.stringify(x) === JSON.stringify(y)
Above works but it will compare all keys I want to exclude c in comparison here. What's the best way to achieve this ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
以下代码从对象
x
中获取所有键,从列表中删除c
,然后执行比较。The following code obtains all the keys from object
x
, removesc
from the list, and then performs the comparison.array.sort 需要一个比较器函数。你可以在这里使用完全相同的东西
array.sort requires a
comparator
function. You can use the exact same thing here一般来说,我不会为了比较它们而对对象进行字符串化。
原因很简单,就是必须确保成员的顺序相同,否则结果将不正确。
例如:
但是,如果您可以确保成员的顺序始终相同,则 stringify 速度很快并且是一个不错的选择。
您可以按顺序使用扩展语法避免“c”属性
或者更通用
的方法是循环遍历对象键或条目
但是,如果您的对象是嵌套的,则需要使用深度相等算法,这当然会更慢。
此处给出了更通用的答案
Generally, I would NOT stringify objects in order to compare them.
The reason is quite simple and is that you MUST to be sure that the order of the members are the same, otherwise the result won't be correct.
Ex:
But, if you can ensure that the order of the members is always the same, stringify is fast and a good option.
You can use the spread syntax in order to avoid the "c" property
Or alternatively
More generic method is to loop over Object key or alternatively to entries
But, if your object is nested, you need to use a deep equality algorithm, which is of course slower.
More generic answer has been given here
感谢大家对我的问题的快速答复,但下面是一个简单的方法,我可以通过它来实现上述逻辑
Thanks everyone for quick responses on my question but below was an easy method from which I could implement the above logic
这又如何呢?
更好的解决方案:
更正 更好的解决方案:
What about this?
better solution:
correct better solution:
使用三元运算符来比较两个对象。
演示:
通过删除不需要的属性,然后使用
JSON.stringify()
进行比较演示:
Using ternary operator to compare both the objects.
Demo :
By deleting the unwanted properties and then compare using
JSON.stringify()
Demo :
这是一个解决方案
Here is a solution