ucef
ucef

Reputation: 557

creating dynami Array of object in javascript

i want to create array with row like this :

 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}, 
          ]

but the attribute in rows( ClickCount, Retweet, LikeCount, ShareCount, Tweet, CommentCount) will be defined from other array,

Array nameMetric contains this name of rows(( ClickCount, Retweet, LikeCount, ...)

so if in nameMetric there is element (likeNumber, TweetNumber, .....) the array dateMetric will contain rows like this :

dateMetric

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

please help, i can reformulate the problem if it's not explained well .

Upvotes: 0

Views: 64

Answers (1)

Greg Ross
Greg Ross

Reputation: 3498

Try this: http://jsfiddle.net/8cetN/

You can look up your name array to define the properties of each row object:

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));

Upvotes: 1

Related Questions