2017-04-10 30 views
-1

我有兩個數組,如果條件滿足,我必須推入新數組$ scope.checkData.I中的匹配對象必須從$ scope.checkData中獲取函數中的「val」並檢入$ 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"); 
        } 

     }); 

在此先感謝。

+0

請添加想要的結果。 –

+0

@ Nina Scholz我更新了預期結果的問題,請檢查一次後請給我。 – pbsbr

回答

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); 
        } 
       }); 
      } 
     }); 
    }) 
} 
+0

嗨, 上面的代碼工作。 您可以將元素數組傳遞給「$ scope.bindData」方法以獲取「$ scope.newArray」中的結果。 –

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; }