I have a JSON object that contain a set of key:values. I want to first check if that first the key matches an array value and then if it does to add the value amount to that same buffers array within that array.
Here’s my code to hopefully show what I mean:
ws.onmessage = function(evt){
cities = JSON.parse(evt.data);
for(var i=0; i<buffer.length; i++) {
if(buffer[i][0] == cities.clusters) {
buffer[i][1][0]++;
}
console.log(buffer);
}
};
This is my buffer array:
var buffer = [['1',[0]],['2',[0]],['3',[0]],['4',[0]]];
This is the JSON output received from the server:
{"clusters": {"London": 4, "Atlanta": 5}, "time": "2012-11-22 19:56:25"}
So what I want is that the buffer array on this iteration becomes:
var buffer = [['London',[4]],['New York',[0]],['Atlanta',[5]],['LA',[0]]];
At every iteration these amounts then get added to and updated.
I don’t know how to do this and I don’t think the for loop will be able to do it.
Thanks
I’m going to pretend that your buffer is this:
Then the loop becomes this:
The expression
cities.clusters[item[0]] || 0uses the value of the respective city or0if not defined.Demo