【问题标题】:Comparing two JSON arrays and get not matching values比较两个 JSON 数组并获得不匹配的值
【发布时间】:2018-06-07 11:16:19
【问题描述】:

我有两个这样的数组

$scope.eClauses = [
  {
    swift_code: "31D",
    eline_description: "e-Example 1"
  },
  {
    swift_code: "41D",
    eline_description: "e-Example 2"
  },
  {
    swift_code: "00D",
    eline_description: "e-Example 3"
  }
];


$scope.masterClauses = [
  {
    swift_code: "31D",
    eline_description: "e-Example 1"
  },
  {
    swift_code: "41D",
    eline_description: "e-Example 2"
  }
];

我想比较这些数组并将不匹配的值获取到另一个这样的数组

$scope.notmatching = [
  {
    swift_code: "00D",
    eline_description: "e-Example 3"
  }
];

到目前为止,我已经尝试过 for each,但没有成功

【问题讨论】:

标签: javascript angularjs


【解决方案1】:

使用Array.filter

let eClauses =[{swift_code:"31D",eline_description:"e-Example1"},{swift_code:"41D",eline_description:"e-Example2"},{swift_code:"00D",eline_description:"e-Example3"}];

let masterClauses = [{swift_code:"31D",eline_description:"e-Example1"},{swift_code:"41D",eline_description:"e-Example2"}];

// Create an array of unique identifier for the objects in masterClause
let keys = Object.keys(masterClauses.reduce((a, {swift_code, eline_description}) => Object.assign(a, {[swift_code + "_" + eline_description] : undefined}), {}));

// Filter in those elements which are missing from the above array
let filtered = eClauses.filter(({swift_code, eline_description}) => !keys.includes(swift_code + "_" + eline_description))

console.log(filtered);

【讨论】:

    【解决方案2】:

    你可以使用 underscore.js 这样很容易

    var c = _.difference($scope.eClauses.map(e => e.swift_code), $scope.masterClauses.map(e =>e.swift_code));
    var array = [];
    array = $scope.eClauses.map(e => {
       if(c.includes(e.swift_code)){
         return e;
       }
    }).filter(r=>r);
    

    【讨论】:

      【解决方案3】:

      您可以尝试像下面的代码一样将丢失的记录从主列表中获取到原始列表中,如下面的代码所示。另请查看this plunker 链接以获取您给定的工作示例场景。

      控制器:

      $scope.getMissingRecord=function(){
         angular.forEach($scope.eClauses, function(item){
         var index = $scope.masterClauses.map(function(e){ return e.eline_description; }).indexOf(item.eline_description);
            if(index==-1) $scope.notmatching.push(item);
          });
      };
      

      模板:

      <button type="button" ng-click="getMissingRecord();">Click To Get Unmatched Clauses</button>
      <ul ng-repeat="um in notmatching">
        <li>{{um.swift_code}}</li>
        <li>{{um.eline_description}}</li>
      </ul>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-04-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-22
        • 1970-01-01
        • 1970-01-01
        • 2019-02-03
        相关资源
        最近更新 更多