在javascript中创建动态对象数组

时间:2012-08-27 19:28:02

标签: javascript arrays

我想用这样的行创建数组:

 dateMetric : [{date : DatNoDuplicate[i] , ClickCount : 0 , Retweet : 0 , LikeCount : 0 , ShareCount : 0, Tweet : 0, CommentCount: 0, SumMetric: 0}, 
           {date : DatNoDuplicate[i] , ClickCount : 0 , Retweet : 0 , LikeCount : 0 , ShareCount : 0, Tweet : 0, CommentCount: 0, SumMetric: 0}, 
          ]

但行中的属性(ClickCount,Retweet,LikeCount,ShareCount,Tweet,CommentCount)将从其他数组定义,

数组nameMetric包含此行名称((ClickCount,Retweet,LikeCount,...)

所以如果在nameMetric中有元素(likeNumber,TweetNumber,.....),则数组dateMetric将包含如下行:

dateMetric

   date : DatNoDuplicate[i] , likeNumber: 0 , TweetNumber: 0 , ... , SumMetric: 0})

请帮助,如果问题得不到解决,我可以重新解决问题。

1 个答案:

答案 0 :(得分:1)

试试这个:http://jsfiddle.net/8cetN/

您可以查找名称数组以定义每个行对象的属性:

var nameMetric = ["ClickCount", "Retweet", "LikeCount", "ShareCount", "Tweet", "CommentCount", "SumMetric"];


var numRows = 4;
var dateMetric = [];

for (var i=0; i<numRows; i++) {

    var row ={};

    nameMetric.forEach(function(name){

        row[name] = 0; // Look up and place the actual value here.   


    });       

    dateMetric.push(row); 

}


console.log(JSON.stringify(dateMetric));