AngularJS检查下载的json是否在工作副本之间有差异

AngularJS check if downloaded json has difference between working copy

本文关键字:之间 副本 工作 下载 检查 json 是否 AngularJS      更新时间:2023-09-26

我下载json,所以:

$scope.getarticles = function(company) {
  $http.get("url", {
      headers: {
        'Content-Type': 'application/json',
        'If-Modified-Since': ''
      }
    })
    .success(function(response) {
      $.each(response, function(ind, el) {
        $scope.articles.push(el);
      });
    })
    .error(function(err, status) {
    });
};

我使用我的 $scope.articles 工作,对于某些对象,我可以更改数据(注意,它也可以有排序 uid 等,不要比较它们) - 如何将我的数据与我从 JSON 获得的数据进行比较?

     $.each($scope.articles, function(ind, el) {
        if (el == $scope.copyArticles)
          console.log("yes");
      });

真的以某种方式做吗?如果是,那怎么做?

没有简单的内置方法,特别是如果您必须忽略某些字段,例如排序 UID。

它只是回到基本的Javascript。

例如,定义一个函数来比较两篇文章是否相等,忽略任何您不关心的字段。为了方便起见,我使用 Lodash 或 UnderscoreJS 的 _.omit() 函数来删除我不关心的键,并使用 angular.equals() 对结果对象进行深入比较。

function articlesAreEqual(article1, article2) {
    return angular.equals(strippedArticle(article1), strippedArticle(article2));
}
function strippedArticle(a) {
    return _.omit(a, 'sortUID' /* add other keys here */);
}

然后,您可以查看是否有任何下载的与现有版本匹配:

$scope.getarticles = function(company) {
  $http.get("url", {
      headers: {
        'Content-Type': 'application/json',
        'If-Modified-Since': ''
      }
    })
    .success(function(response) {
      $.each(response, function(ind, el) {
        if (articlesAreEqual($scope.articles[ind], el)) {
            console.log('Article #' + (ind + 1) + ' is the same.');
        } else {
            console.log('Article #' + (ind + 1) + ' differs.');
            $scope.articles.splice(ind, 1, el); // replace the existing one
        }
      });
    })
    .error(function(err, status) {
    });
};