如何处理和检查唯一ID?

时间:2015-01-23 20:21:21

标签: javascript arrays transactions rows indexof

我有多个交易行,我想看看我是否可以在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,因此我无法处理每条线路。救命啊!

1 个答案:

答案 0 :(得分:1)

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

&#13;
&#13;
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);
});
&#13;
#data{
  border: grey 1px solid;
}

#filteredData{
  border: grey 1px solid;
}
&#13;
<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>
&#13;
&#13;
&#13;

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