返回AngularJS中两个数组值之间的匹配

时间:2016-08-07 21:34:23

标签: javascript angularjs ionic-framework

在两个数组元素之间返回匹配数组有问题,请帮助很重要 这是我的代码

      $scope.MacA = [
  {
    name: '24:fd:52:c3:d8:35',
    sector: 'A23'
  }, 

  {
    name: '56:db:30:4b:57:45',
    sector: 'It support'
  },
  {
    name: 'b6:b6:76:6b:e9:00',
    sector: 'A24'
  },
  {
    name: 'e8:74:e6:a1:14:16',
    sector: 'Vodafone Guest'
  },
  {
    name: 'dc:4a:3e:b7:32:0e',
    sector: 'Direct HP officejet'
  }
  ,
  {
    name: '7c:4c:a5:32:13:29',
    sector: 'skyb7'
  }

] 和数组2是

scope.match = ['dc:4a:3e:b7:32:0e','7c:4c:a5:32:13:29' ];

这是返回匹配项的函数

 $scope.getList = function(){
      // $scope.wifiList = WifiService.list();
      var c = $scope.MacA;
      var m = WifiService.list();
      for(var i = 0;i < c.length;i++) {
        for(var j = i;j < m.length;j++) { // Notice the j = i;
          if (c[i].name === m[j]) {
            $scope.result = c[i].sector;
        // $scope.result = 'Its working';
        break;
          } else {
             $scope.result = "Sorry!";
          }
        };
      };
  return $scope.result;
}

3 个答案:

答案 0 :(得分:0)

您没有指定您想要的结果,但这里有一个查找匹配项的可能版本。

var result = [];
match.forEach(m => result.push(MacA.find(macA => macA.name === m)));

答案 1 :(得分:0)

   MacA = [
  {
    name: '24:fd:52:c3:d8:35',
    sector: 'A23'
  }, 

  {
    name: '56:db:30:4b:57:45',
    sector: 'It support'
  },
  {
    name: 'b6:b6:76:6b:e9:00',
    sector: 'A24'
  },
  {
    name: 'e8:74:e6:a1:14:16',
    sector: 'Vodafone Guest'
  },
  {
    name: 'dc:4a:3e:b7:32:0e',
    sector: 'Direct HP officejet'
  },
  {
    name: '7c:4c:a5:32:13:29',
    sector: 'skyb7'
  }
]

Match = ['dc:4a:3e:b7:32:0e','7c:4c:a5:32:13:29' ];

MacA.filter(({name}) => Match.includes(name)).map(({sector}) => sector)
// RETURNS // ["Direct HP officejet", "skyb7"]

所以,根据你的代码,如下所示:

 $scope.getList = function(){
   return $scope.result = $scope.MacA.filter(({name}) => $scope.match.includes(name)).map(({sector}) => sector)
}

答案 2 :(得分:0)

我重构了你的一些代码。

 $scope.getList = function(){
  var devices = $scope.MacA;
  var macList = WifiService.list();
  var results = devices.reduce((acc, device) => acc.concat(macList.find(current.name)? [current.sector]:[]), []);
  return results.length? $scope.results = results : $scope.results = 'Sorry!';
}