如何用lodash对2个对象进行深度比较? [英] How to do a deep comparison between 2 objects with lodash?

查看:5224
本文介绍了如何用lodash对2个对象进行深度比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个不同的嵌套对象,我需要知道它们的嵌套属性是否存在差异。

I have 2 nested objects which are different and I need to know if they have difference in one of their nested properties.

var a = {};
var b = {};

a.prop1 = 2;
a.prop2 = { prop3: 2 };

b.prop1 = 2;
b.prop2 = { prop3: 3 };

对于更多嵌套属性,对象可能会复杂得多。但这个是一个很好的例子。我可以选择使用递归函数或者使用lodash ...

The object could be much more complex with more nested properties. But this one is a good example. I have the option to use recursive functions or something with lodash...

推荐答案

一个简单而优雅的解决方案是使用 _。isEqual ,执行深度比较:

An easy and elegant solution is to use _.isEqual, which performs a deep comparison:

var a = {};
var b = {};

a.prop1 = 2;
a.prop2 = { prop3: 2 };

b.prop1 = 2;
b.prop2 = { prop3: 3 };

_.isEqual(a, b); // returns false if different

,则返回false但是,此解决方案不会显示哪个属性不同。

However, this solution doesn't show which property is different.

http://jsfiddle.net/bdkeyn0h/

这篇关于如何用lodash对2个对象进行深度比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆