wharfdale
wharfdale

Reputation: 752

Increment JS key with number within a loop

I have nested a second for loop and trying to create an array key of wk1, wk2 etc for all 52 weeks of the year. Then add that to the item object.

Desired result:

item.wk1 = phpjs.amazon_ratings[i].wk1;
item.wk2 = phpjs.amazon_ratings[i].wk2;
etc...
var i;
var j;
for (i = 0; i < phpjs.amazon_ratings.length; i++) {

  // Create the item object
  var item = {};

  // Add default array keys `sku`, and their values from the `amazon_ratings` array as we loop through each item.
  item.sku = phpjs.amazon_ratings[i].sku;
  item.asin = phpjs.amazon_ratings[i].asin;
  item.current_week_rating = phpjs.amazon_ratings[i].rating;
  item.total_ratings = phpjs.amazon_ratings[i].ratings_total;
  item.category = phpjs.amazon_ratings[i].category;

  // Loop 52 times and create array keys such as: WK1, WK2, WK3
  for (j = 1; j < 53; j++) {
    item.wk[j] = phpjs.amazon_ratings[i].wk[j];
  }

  // Add it to the array
  tabledata.push( item );
}

However it's failing with: Uncaught TypeError: Cannot set property '1' of undefined

Upvotes: 0

Views: 104

Answers (1)

Lars van den Bosch
Lars van den Bosch

Reputation: 750

it should be item['wk' + j].

And remember that a year does not have 52 weeks. U have to check it for each year.

Upvotes: 1

Related Questions