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

标签 javascript angularjs lodash

我有一个复杂的 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/

相关文章:

javascript - MongooseJS 模式关系

java - request.getSession().getId() 和 request.getSession(false) 的区别?

angularjs - Angular Controller 未注册错误

java - Angularjs 中的模块是什么?

javascript - 当值相等时,React hooks useState setValue 仍然会重新渲染一次

javascript - Highcharts - 甘特图绘图问题

javascript - 访问嵌套 ng-repeat 中的父索引

javascript - javascript中的数组过滤数据

javascript - 使用与 Lodash 的差异

Angular 4 HttpClient 查询参数