如果条件退出,如何推入新数组?

时间:2017-04-10 14:29:35

标签: javascript angularjs arrays

我有两个数组,如果条件满足,我必须将$ scope.checkData中的匹配对象推入新数组。我必须得到" val"来自$ scope.checkData的函数,并检入$ scope.postData

使用Javascript:

  $scope.postData= [
     { "pid": 1, "id": 1, "status": 1 }, 
     { "pid": 1, "id": 2, "status": 0 }, 
     { "pid": 1, "id": 3, "status": 1 }, 
     { "pid": 1, "id": 4, "status": 1 }, 
     { "pid": 1, "id": 5, "status": 0 }, 
     { "pid": 1, "id": 6, "status": 1 }, 
     { "pid": 1, "id": 7, "status": 1 }
  ];

   $scope.checkData= [
         { "val": 1, "txt": "one" }, 
         { "val": 2, "txt": "two" }, 
         { "val": 3, "txt": "three" }, 
         { "val": 4, "txt": "four" }, 
         { "val": 5, "txt": "five" }, 
         { "val": 6, "txt": "six" }, 
         { "val": 7, "txt": "seven" 
  }];

   $scope.bindData = function (id) {

          console.log(id);
          $scope.someAry = [];
          id.forEach(function (elem) {
              $scope.postData.forEach(function (val) {
              console.log(elem);
              if (val.id== elem && val.status == true) {
                      alert("match  found");
                  }
             else {
                      alert("match not found");
                  }

      });

先谢谢。

2 个答案:

答案 0 :(得分:1)

$scope.bindData = function (id) {
    console.log(id);
    $scope.someAry = [];
    id.forEach(function (elem) {
        $scope.postData.forEach(function (val) {
            console.log(elem);
            if (val.id == elem && val.status == 1) {
                $scope.checkData.forEach(function (cval) {
                    if (cval.val == elem) {
                        $scope.newArray.push(cval);
                    }
                });
            }
        });
    })
}

答案 1 :(得分:0)

您可以使用哈希表和单个循环来设置哈希表,使用一个循环来过滤checkData



var $scope = {},
    hash = Object.create(null);

$scope.postData = [{ pid: 1, id: 1, status: 1 }, { pid: 1, id: 2, status: 0 }, { pid: 1, id: 3, status: 1 }, { pid: 1, id: 4, status: 1 }, { pid: 1, id: 5, status: 0 }, { pid: 1, id: 6, status: 1 }, { pid: 1, id: 7, status: 1 }];
$scope.checkData = [{ val: 1, txt: "one" }, { val: 2, txt: "two" }, { val: 3, txt: "three" }, { val: 4, txt: "four" }, { val: 5, txt: "five" }, { val: 6, txt: "six" }, { val: 7, txt: "seven" }];

$scope.postData.forEach(function (a) {
    hash[a.id] = a.status === 1;
});
$scope.newArray = $scope.checkData.filter(function (a) {
    return hash[a.val];
});

console.log($scope.newArray);

.as-console-wrapper { max-height: 100% !important; top: 0; }