2014-12-23 32 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)它可能会给你很好的提示如何简化你的代码。 –

相关问题