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~