Drw*_*ite 20 javascript jquery json
我试图比较这两个JSON对象:
<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 />
Run Code Online (Sandbox Code Playgroud)
我用javascript得到了值,我试着用它来比较:JSON.stringify(remoteJSON) == JSON.stringify(localJSON)但是这返回false:看起来属性的顺序很重要.
我甚至尝试与这个解决方案进行深入比较,总是得到错误的回报.
是否有一种快速的方法来解决jQuery的问题(即用于比较JSON的库)?
Nic*_*las 25
Lodash _.isEqual允许你这样做:
var
remoteJSON = {"allowExternalMembers": "false", "whoCanJoin": "CAN_REQUEST_TO_JOIN"},
localJSON = {"whoCanJoin": "CAN_REQUEST_TO_JOIN", "allowExternalMembers": "false"};
console.log( _.isEqual(remoteJSON, localJSON) );Run Code Online (Sandbox Code Playgroud)
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>Run Code Online (Sandbox Code Playgroud)
小智 12
DeepCompare 方法比较两个 json 对象..
deepCompare = (arg1, arg2) => {
if (Object.prototype.toString.call(arg1) === Object.prototype.toString.call(arg2)){
if (Object.prototype.toString.call(arg1) === '[object Object]' || Object.prototype.toString.call(arg1) === '[object Array]' ){
if (Object.keys(arg1).length !== Object.keys(arg2).length ){
return false;
}
return (Object.keys(arg1).every(function(key){
return deepCompare(arg1[key],arg2[key]);
}));
}
return (arg1===arg2);
}
return false;
}
console.log(deepCompare({a:1},{a:'1'})) // false
console.log(deepCompare({a:1},{a:1})) // trueRun Code Online (Sandbox Code Playgroud)
小智 7
Lodash isEqual() method is the best way to compare two JSON object.
This will not consider the order of the keys in object and check for the equality of object. Example
const object1={
name:'ABC',
address:'India'
}
const object2={
address:'India',
name:'ABC'
}
JSON.stringify(object1)===JSON.stringify(object2)
// false
_.isEqual(object1, object2)
//true
Run Code Online (Sandbox Code Playgroud)
Reference-https://lodash.com/docs/#isEqual
If sequence is not going to change than JSON.stringify() will be fast as compared to Lodash isEqual() method
Reference-https://www.measurethat.net/Benchmarks/Show/1854/0/lodash-isequal-test
| 归档时间: |
|
| 查看次数: |
64056 次 |
| 最近记录: |