gpt4 book ai didi

javascript - 使用深度比较或 json.stringify 比较两个对象?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:55:20 26 4
gpt4 key购买 nike

我有一个复杂的 JSON 对象,我想如下进行比较:

$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 个对象时忽略该属性。

 console.log(angular.equals($scope.new,$scope.copy)); 

因此,在进行研究时,我得到了以下答案,该答案使用具有 emit 选项的 lodash,但问题是我想省略了创建副本,我想如果使用 lodash,我的性能会下降。

Exclude some properties in comparison using isEqual() of lodash

所以现在我正在考虑将对象转换为字符串,然后进行比较,我想这会很快,但问题是我将如何在字符串比较时忽略该属性?

像这样:

var str1 = JSON.stringify(JSON.stringify($scope.new));

var str2 = JSON.stringify(JSON.stringify($scope.copy));

console.log(str1==str2);

注意:我想在比较 2 个对象时忽略 isParent 属性。

比较 2 个对象的最佳方法是什么?

最佳答案

在这些情况下,转换为字符串并不是最好的方法。将它们作为对象保存。

使用加载灰:

const propertiesToExclude = ['isParent'];
let result = _.isEqual(
_.omit(obj1, propertiesToExclude),
_.omit(obj2, propertiesToExclude)
);

使用普通的 AngularJS,创建删除不需要的属性的对象副本,然后比较它们:

let firstObj = angular.copy(obj1);
let secondObj = angular.copy(obj2);
const propertiesToExclude = ['isParent'];
function removeNotComparatedProperties(obj) {
propertiesToExclude.forEach(prop => {
delete obj[prop];
});
}

removeNotComparatedProperties(firstObj);
removeNotComparatedProperties(secondObj);
angular.equals(firstObj, secondObj);

关于javascript - 使用深度比较或 json.stringify 比较两个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46302169/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com