比较具有深度比较或json.stringify的两个对象? [英] Compare two object with deep comparision or with json.stringify?
问题描述
我有一个复杂的JSON对象,我想像下面这样比较:
I am having a complex JSON object which I want to compare like below :
$scope.new = [
{
"name": "Node-1",
"isParent": true,
"text" : [
{
"str" : "This is my first Node-1 string",
"parent":[]
},
{
"str" : "This is my second Node-1 string",
"parent":[]
}],
"nodes": [
{
"name": "Node-1-1",
"isParent": false,
"text" : [
{
"str" : "This is my first Node-1-1 string",
"parent":[]
},
{
"str" : "This is my second Node-1-1 string",
"parent":[]
}],
"nodes": [
{
"name": "Node-1-1-1",
"isParent": false,
"text" : [
{
"str" : "This is my first Node-1-1-1 string",
"parent":[]
},
{
"str" : "This is my second Node-1-1-1 string",
"parent":[]
}],
"nodes": []
}
]
}
]
}
]
但是在比较时,我也想忽略1个属性,但是当我使用Angular.js时,我没有在angular.equal
中看到任何选项,该选项在比较2个对象时会忽略该属性.
But while comparing I want to ignore 1 property also but as I am using Angular.js I don't see any option in angular.equal
which will omit that property while comparing 2 object.
console.log(angular.equals($scope.new,$scope.copy));
因此,在进行研究时,我给出了以下答案,该答案使用具有发出选项的lodash,但问题是我忽略了创建副本,并且在lodash的情况下会降低性能.
So while doing research I came with below answer which is using lodash having emit option but problem is I guess omit create a copy and I guess I will have performance degradation in case of lodash.
所以现在我正在考虑将对象转换为字符串,然后进行比较,我想那会很快,但是问题是我在字符串比较时如何忽略该属性?
So now I am thinking to convert object so string and then do comparison and I guess that will be fast but problem is how I will omit that property while string comparison?
类似这样的东西:
var str1 = JSON.stringify(JSON.stringify($scope.new));
var str2 = JSON.stringify(JSON.stringify($scope.copy));
console.log(str1==str2);
注意:我想在比较2个对象时忽略isParent
属性.
Note: I want to ignore isParent
property while comparing 2 object.
比较2个对象的最佳方法是什么?
What would be the best way to do compare 2 object?
推荐答案
var objA = {
isParent: true,
foo: {
isParent: false,
bar: "foobar"
}
};
var objB = {
isParent: false,
foo: {
isParent: true,
bar: "foobar"
}
};
var comparator = function(left, right, key) {
if (key === 'isParent') return true; // if the key is 'isParent', mark the values equal
else return undefined; // else fall back to the default behavior
}
var isEqual = _.isEqualWith(objA, objB, comparator);
console.log(isEqual); // true
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
要排除多个属性,请相应地扩展比较器功能:
To exclude multiple properties, extend the comparator function accordingly:
var comparator = function(left, right, key) {
if (key === 'isParent' || key === 'anotherKey') return true;
else return undefined;
}
您还可以根据自己的喜好在语法上使用多种不同的方法-一个switch语句,一个您迭代的数组...
You could also use a number of different approaches syntactically, depending on what you prefer -- a switch statement, an array that you iterate...
这篇关于比较具有深度比较或json.stringify的两个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!