There is a code that adds data from arrays

var data = [{ id: 100, chance: 10 }, { id: 100, chance: 30 }, { id: 200, chance: 10 }, { id: 300, chance: 5 }, { id: 200, chance: 30 }, { id: 100, chance: 15 }]; var result = {}; for (var element of data) { if (result[element.id] == undefined) result[element.id] = 0; result[element.id] += element.chance; } for (var id in result) console.log("id: " + id + ", chance: " + result[id]); 

This code is executed only once after the page loads - let it be socket.on('load_data',...) But another socket socket request is also constantly coming to the page: socket.on('bet_data',...) ..

Together with bet_data comes data in this form data = { id: 400, chance: 10 } .

The events look like this:

 socket.on('load_data', function(data) { var data = [{ id: 100, chance: 10 }, { id: 100, chance: 30 }, { id: 200, chance: 10 }, { id: 300, chance: 5 }, { id: 200, chance: 30 }, { id: 100, chance: 15 }]; var result = {}; for (var element of data) { if (result[element.id] == undefined) result[element.id] = 0; result[element.id] += element.chance; } for (var id in result) console.log("id: " + id + ", chance: " + result[id]); }); socket.on('bet_data', function(data) { var data = { id: 400, chance: 10 }; // тут нужно сделать сделать обновление переменной result, и (занести/добавить к существующему) новый результат. }); 

I hope explained clearly ..

  • do the result variable - global - Grundy
  • when executing code with such an object as in bet_data - error data [Symbol.iterator] is not a function - stoner
  • Well, it's obvious because you have data in load_data - an array, and in bet_data, the only object is Grundy
  • Well, I understand what to do with it?) - stoner

1 answer 1

A simple option is to make the result variable global and put the code to add to the result in the function:

 var result = {}; function addToResult(id, chance) { if (result[id] == undefined) result[id] = 0; result[id] += chance; } //socket.on('load_data' setTimeout(function() { var data = [{ id: 100, chance: 10 }, { id: 100, chance: 30 }, { id: 200, chance: 10 }, { id: 300, chance: 5 }, { id: 200, chance: 30 }, { id: 100, chance: 15 }]; for (var element of data) addToResult(element.id, element.chance); }, 10); //socket.on('bet_data' setTimeout(function() { var data = { id: 400, chance: 10 }; addToResult(data.id, data.chance); //проверка результата for (var id in result) console.log("id: " + id + ", chance: " + result[id]); }, 100);