2016-09-26 50 views
1
{ 
    "ordersList": [{ 
     "ordersDto": { 
      "testMast": { 
       "testId": 9, 
       "testName": "HIV" 
      }, 
      "sample": { 
       "sampleId": 9050 
      } 
     } 
    }, { 

     "ordersDto": { 
      "testMast": { 
       "testId": 1, 
       "testName": "VDRL" 
      }, 
      "sample": null 
     } 
    }, { 

     "ordersDto": { 
      "testMast": { 
       "testId": 11, 
       "testName": "HIV1&2" 
      }, 

      "sample": null 
     } 
    }, { 
     "ordersDto": { 
      "testMast": { 
       "testId": 3, 
       "testName": "HCB" 
      }, 

      "sample": { 
       "sampleId": 9050 
      } 
     } 
    }, { 

     "ordersDto": { 
      "testMast": { 
       "testId": 10, 
       "testName": "HIV 1&2 Test1" 
      }, 

      "sample": { 
       "sampleId": 9051 
      } 
     } 

    }] 
} 

迭代需要在陣列中獲取非重複的樣本ID,密鑰值對存儲和角

sample Id = 9050, 9051. 

此外,我需要爲每個檢體ID讀取測試名稱,重複樣品ID的我需要將測試名稱添加到相同的數組中。

testName = HIV, HCB // for 9050 
testName = HIV 1&2 Test1" // for 9051 

如何在一次迭代中填充這兩個數組,還可以根據樣本Id值獲取testName。 是否有任何鍵值對存儲在角?

曾嘗試使用下面的代碼,這不正常工作。

if (vm.ordersList== 1) { // incase of one sample Id 
       res.push(vm.ordersList[0].ordersDto.testMast.testName.slice(0, 4)); 
       sampleId.push(angular.copy(vm.ordersList[0].ordersDto.sample.sampleId)); 
       sampleRcvdDate.push(angular.copy(vm.ordersList[0].ordersDto.sample.sampleRcvdOn)); 
       } else { 
       angular.forEach(vm.ordersList, function(item) { // multiple sample id's 
        if (item.sample != null) { 
         if(item.sample.sampleId != null && sampleId.indexOf(item.sample.sampleId) == -1){ 
         res.push(item.testMast.testName.slice(0, 4)); 
         sampleId.push(angular.copy(item.sample.sampleId)); 
         sampleRcvdDate.push(angular.copy(item.sample.sampleRcvdOn)); 
         } 
        } 
       }) 
       } 
+0

您可以將密鑰和值對存儲在地圖中 – Hmahwish

+0

我可以在插入後更新相同的地圖值。 – user630209

+0

是的你可以有一個sampleId作爲鍵和一個testName的數組 – Hmahwish

回答

2

sampleIdTestNameMap將sampleId作爲key和testName列表作爲值。

var sampleIdTestNameMap = {}; 
angular.forEach(vm.ordersList, function(item) { 
    if (item.ordersDto.sample != null && item.ordersDto.sample.sampleId != null) { 

     if (sampleId.indexOf(item.ordersDto.sample.sampleId) == -1) { 
      sampleId.push(angular.copy(item.ordersDto.sample.sampleId)); 
      sampleIdTestNameMap[item.ordersDto.sample.sampleId] = [item.ordersDto.testMast.testName]; 
     } else { 
      var tempList = []; 
      tempList = sampleIdTestNameMap[item.ordersDto.sample.sampleId]; 
      tempList.push(item.ordersDto.testMast.testName); 
      sampleIdTestNameMap[item.ordersDto.sample.sampleId] = tempList; 
     } 
    } 
});