2014-12-23 26 views
0

我有兩個陣列,一個是對象的這樣的陣列的對象的屬性值:獲取使用另一個數組作爲參考

[ 
    Object {ID: "2006", Description: "ABCDEFG"} 
    Object {ID: "2102", Description: "HIJKLMN"} 
    Object {ID: "2616", Description: "OPQRSTU"} 
] 

而另一個是與所述屬性的陣列

["ID", "Description"] 

我試圖使用JQuery 。每個函數捕獲使用數組作爲參考值,並創建一個HTML表,就像這樣:

 var columns = new Array(); 
     var strTable = ''; 
     var tHead = ''; 
     var tBody = ''; 

     //Capture the columns 
     $.each(arrObjects, function (a, b) { 
      columns=Object.getOwnPropertyNames(b) 
     }); 

     //Make the Table Head; 
     $.each(columns, function (a, b) { 
      tHead += '<th>'+ b +'</th>' 
     }); 

     //Create table body 
     $.each(arrObjects, function (aa, bb) { 
      tBody += '<tr>' 

      $.each(columns, function (a, b) { 
       tBody += '<td>'+ bb.b +'</td>' 
      }); 

      tBody += '</tr>' 
     }) 

     strTable = '<table class="table"><thead><tr>' + tHead + '</tr></thead><tbody>' + tBody + '</tbody></table>' 

但使用這種方式,我總是得到值undefined

你能幫我創建一個函數,接收一個對象數組,並檢索一個表?或者幫我找出我在做什麼錯了也沒關係。

+1

'bb.b'是名爲'塔屬性你想'bb''bb''bb [b]''使用'b'的*值*作爲鍵。 [JavaScript屬性訪問:點符號與括號?](http://stackoverflow.com/q/4968406/1960455) –

+0

你說得對。請將它作爲答覆發佈。謝謝。 – MarceloBarbosa

+0

這是肯定的重複到另一個問題,但我目前沒有找到一個好的。 –

回答

1

你有每個環內的一些錯誤,試試這個片段,並密切關注的變量裏面//Create table body

var columns = []; 
 
var strTable = ''; 
 
var tHead = ''; 
 
var tBody = ''; 
 
var arrObjects = [ 
 
{ID: "2006", Description: "ABCDEFG"}, 
 
{ID: "2102", Description: "HIJKLMN"}, 
 
{ID: "2616", Description: "OPQRSTU"} 
 
]; 
 

 
//Capture the columns 
 
$.each(arrObjects, function (a, b) { 
 
    columns=Object.getOwnPropertyNames(b); 
 
}); 
 

 
//Make the Table Head; 
 
$.each(columns, function (a, b) { 
 
    tHead += '<th>'+ b +'</th>'; 
 
    console.log(tHead); 
 
}); 
 

 
//Create table body 
 
$.each(arrObjects, function (idx, obj) { 
 
    tBody += '<tr>'; 
 

 
    $.each(obj, function (obj_idx, value) { 
 
    console.log(value); 
 
    tBody += '<td>'+ value +'</td>'; 
 
    }); 
 

 
    tBody += '</tr>'; 
 
}); 
 

 
strTable = '<table class="table"><thead><tr>' + tHead + '</tr></thead><tbody>' + tBody + '</tbody></table>'; 
 

 
$('body').html(strTable);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<body> 
 
</body>

+0

@dome幹得好,我明白了。非常感謝你的時間和幫助;但是,假設這個對象比這兩個屬性的屬性更多,我必須使用columns數組來獲取必要的數據,並使用括號括起來,例如't.niese'。你的答案對這個範圍是正確的,但我會改變第二個,繼續使用列Array。希望你明白了。再次感謝。 – MarceloBarbosa

+0

@MarceloBarbosa看看這個[SO回答](http://stackoverflow.com/a/10301494/220272)它可能會給你很好的提示如何簡化你的代碼。 –

相關問題