0

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

3
  • 1
    You forgot to initialize item.wk to a new empty array (or object or whatever you expect it to be). Commented Mar 17, 2021 at 13:20
  • Also make sure you appropriately declare i and j. Commented Mar 17, 2021 at 13:21
  • Adding properties as you say you want them is possible, but it would be a strange way of doing things. Much much easier and more flexible to have an actual array. Commented Mar 17, 2021 at 13:22

1 Answer 1

1

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

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.