如何处理和检查唯一ID?

How to process and check unique IDs?

我有多个交易行,我想看看我是否可以在 for 循环中处理每个行,或者至少将它们存储在一个数组中,以便我可以查找并检查交易 ID已被引用。

我的数据如下:

PersonID | TranID | LineID | Info
123      |  1     | 0      | Apples
123      |  1     | 1      | Oranges
145      |  2     | 0      | Bananas
145      |  2     | 1      | Popcorn
145      |  2     | 2      | Mushrooms

以及我想唯一解析的内容:

123
#1
Apples
Oranges

~~

145
#2
Bananas
Popcorn
Mushrooms

我在想:

var transaction = new Array();

for (var i = 0; datarows != null && i <= datarows.length; i++){

   if datarows[i].tranID is not in transaction{

   write the rows
   transaction.push(datarows[i].tranID)

   } else {
   return;
 }
}

问题是..我实际上并没有存储行 ID,所以我无法处理每一行。求助!

好的..这是你需要做的(假设你正在使用 jQuery - 我通常觉得它更容易) -

var dataArray = [
  {personId: 123, tranId: 1, lineId: 0, info: 'Apples'},
  {personId:123, tranId:1, lineId:1, info:'Oranges'},
  {personId:145, tranId:2, lineId:0, info:'Bananas'},
  {personId:145, tranId:2, lineId:1, info:'Popcorn'},
  {personId:145, tranId:2, lineId:2, info:'Mushrooms'}
];

//Don't bother about this
$.each(dataArray, function(colIndex, item){ 
  
  var row = $('<tr/>'); 
  
  $.each(item, function(rowIndex, it){       
    row.append($('<td/>').text(it));    
  });
    
  $('#data tbody').append(row);
});

// Have an array for filtered objects
var filteredArray = [];

// Iterate through data array
$.each(dataArray, function(index, item){
  
  if(filteredArray.length == 0)
    filteredArray.push(item);
  
  // a flag to tell you if the data exists in the filtered array or not
  var addItem = true;
  
  // Check if the data exists in the filtered array
  var filteredItem = $.grep(filteredArray, function(filItem, filIndex, filAll){
    
    // Here is where you check whatever conditions you want
    if(filItem.personId == item.personId && filItem.tranId == item.tranId) {
     addItem = false;
      return false;
    }      
  });
  
  // Add the data
  if(addItem)
    filteredArray.push(item);
});


//Don't bother about this
$.each(filteredArray, function(colIndex, item){ 
  
  var row = $('<tr/>'); 
  
  $.each(item, function(rowIndex, it){       
    row.append($('<td/>').text(it));    
  });
    
  $('#filteredData tbody').append(row);
});
#data{
  border: grey 1px solid;
}

#filteredData{
  border: grey 1px solid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="data">
  <thead>
  <th>PersonID</th>
  <th>TranID</th>
  <th>LineID</th>
  <th>Info</th>  
  </thead>
  <tbody></tbody>
</table>
<br/><br/>

<table id="filteredData">
   <thead>
  <th>PersonID</th>
  <th>TranID</th>
  <th>LineID</th>
  <th>Info</th>  
  </thead>
  <tbody></tbody>
</table>

此外,这是 CodePen - http://codepen.io/aswinramakrish/pen/YPQZBj