如何比较两个JSON具有相同的属性没有顺序? [英] How to compare two JSON have the same properties without order?

查看:167
本文介绍了如何比较两个JSON具有相同的属性没有顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图比较这两个JSON对象:

I have tried to compare those two JSON objects:

<input type="hidden" id="remoteJSON" name="remoteJSON" value='{"allowExternalMembers": "false", "whoCanJoin": "CAN_REQUEST_TO_JOIN"}' /><br />
<input type="hidden" id="localJSON" name="localJSON" value='{"whoCanJoin": "CAN_REQUEST_TO_JOIN", "allowExternalMembers": "false"}' /><br />

我用javascript获取值,我试图与以下内容进行比较: JSON.stringify (remoteJSON)== JSON.stringify(localJSON)但返回false:似乎属性的顺序很重要。

I got values with javascript and I tried to compare with : JSON.stringify(remoteJSON) == JSON.stringify(localJSON) but this return false: it seems that the order of the properties is important.

和我甚至尝试与此解决方案进行深入比较,并且总是得到错误的回报。

And I even tried deep compare with this solution and always got a false return.

有没有一种快速的方法来解决jQuery的问题(​​即用于比较JSON的库)?

Is there a fast way to do the issue with jQuery (i.e. libraries for comparing JSON) ?

推荐答案

Lodash _。isEqual 允许您要做到这一点:

Lodash _.isEqual allows you to do that:

var
remoteJSON = {"allowExternalMembers": "false", "whoCanJoin": "CAN_REQUEST_TO_JOIN"},
    localJSON = {"whoCanJoin": "CAN_REQUEST_TO_JOIN", "allowExternalMembers": "false"};
    
console.log( _.isEqual(remoteJSON, localJSON) );

<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>

这篇关于如何比较两个JSON具有相同的属性没有顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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