简体   繁体   English

打印Javascript对象数组的有效方法?

[英]Efficient way to print Javascript Array of Objects?

I have an Array of Objects as similar to, 我有一个类似的对象数组,

var aData = [{"name":"abc","age":12},{"name":"xyz","age":20}];

All the Objects will have the same properties. 所有对象将具有相同的属性。 Now i'll have to create a string similar to, 现在,我必须创建一个类似于以下内容的字符串,

name age 名字 年龄
abc 12 abc 12
xyz 20 xyz 20

I'm able to achieve this by doing as below, 我可以通过以下方式实现这一目标,

for(i=0;i<aData.length;i++){

  // Loop for printing the heading
  if(i==0){      
     for(key in aData[i]){
       outputString += key + "\t"; 
      }
     outputString += "\n";
  }

  //Lopp for printing the values 
  for(key in aData[i]){
     outputString += aData[i].key + "\t";
  }
  outputString += "\n";
}

The above implementation works fine for me, but i'm trying to find if there is an optimal way of doing this. 上面的实现对我来说很好,但是我试图找到是否有一种最佳的方法。 In my case, the array size depends on the value returned by database which might be huge. 就我而言,数组的大小取决于数据库返回的值,该值可能很大。 I feel i'm using an additional loop as well as an if condition that would be checked for every iteration. 我觉得我正在使用一个额外的循环以及将为每个迭代检查的if条件。

You can possibly pull the first inner loop 您可以拉第一个内循环

 for(key in aData[i]){
   outputString += key + "\t"; 
  }
 outputString += "\n";

outside the main loop. 在主循环之外。 You have to check that the length of aData is not zero and if it is not then you use the first object in the array to print the headings. 您必须检查aData的长度不为零,如果不为零,则使用数组中的第一个对象打印标题。

Another improvement is to gather all the property names from the first object outside the main loop (so you do that only once) and use these names to access the properties of all objects thereafter. 另一个改进是从主循环外的第一个对象收集所有属性名称(因此,您只需执行一次),然后使用这些名称访问所有对象的属性。

I am not sure of the actual performance gain, but you can try it out. 我不确定实际的性能提升,但是您可以尝试一下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM