0

Not sure what I'm doing wrong here. Basically I am retrieving info from an API. setting 2 properties from the JSON data to an array named "name" and "profit". I would like to combine them so that the "name" array is the "key" in my object called "itemProfit" and the value of that key is the profit array.

Example:

name = ['item1'];
profit = [1000];

itemProfit = {item1: 1000};

I'm able to properly output the name / profit array to the console but my error is generating at line:

itemProfit.name[i] = profit[i];

The full code is as follows:

btn_top.addEventListener("click", function () {
  fetch(url)
    .then(function(response) {
      return response.json();
    })
    .then(function(myJson) {
      let name = [];
      let profit = [];
      Object.values(myJson).forEach(e=> {
        name.push(e.name);
        profit.push(e.sell_average - e.buy_average);
      });
      var itemProfit = {}
      for (i=0; i<name.length; i++) {
        itemProfit.name[i] = profit[i]; // where error occurs
      };
      // console.log(name);
      // console.log(profit);
      console.log(itemProfit);
    });
});

Error Message:

main.js:52 Uncaught (in promise) TypeError: Cannot set property '0' of undefined
    at main.js:52

Any help would be appreciated thank you~

Nick
  • 624
  • 8
  • 24
  • Try posting the full error message. Also, you should have a `.catch()` after the `.then` to catch possible errors like the one you have – iagowp Dec 13 '18 at 00:24

1 Answers1

2

Well, what your code is doing is trying to access itemProfit.name[0]. itemProfit doesn't have a property name, so when you try to access [0] of undefined, you get that error

itemProfit.name[i]

What you actually want to do is:

itemProfit[name[i]] = profit[i]

This way you are assigning profit[i] to the key on itemProfit corresponding to name[i]

iagowp
  • 2,428
  • 1
  • 21
  • 32