William Calhoun William Calhoun - 1 year ago 58
Javascript Question

Combining Javascript Arrays into key value look up

I have a Javascript object called Data that looks like:

Object {
zip: Array[14631],
lat: Array[14631],
lng: Array[14631],
surge: Array[14631]

Data looks like

Zipcode, Lat, Lng, Surge
10025, 47.323, -93.43, 1.7

So to access elements I can do something like:
and it will return the 'ith' element of the zip array.
I can do the same with all the arrays.

What I want is a data structure such that I can do:
and it will return all matching element in the other arrays.
So lets say I had 5 entries with zipcode = 10025, the data[10025] would return:


So that I could then double iterate through

for zip in data['zip']{
for i in data[zip] {
print data[zip]['lats'][i]

I think this is a simple enough problem but I don't have much experience with javascript and can't seem to get it. Any help is much appreciated.

Another way to phrase this is I would like an object that looks like:

data[array size of N]

Where each element of that array holds 3 arrays of size M

Answer Source

Why not do it something like this...

data = {
    "10025": [
            "Lat": 47.323,
            "Lng": -93.43,
            "Surge": 1.7
            "Lat": 47.323,
            "Lng": -93.43,
            "Surge": 1.7
            "Lat": 47.323,
            "Lng": -93.43,
            "Surge": 1.7

Then you could access the zip by data["10025"] and loop through the array of locations.

var data = {};
for(var i = 0; i < obj.zip.length;i++){
    var zip = obj.zip[i]
    data[zip] = data[zip] || [];
        zip: obj.zip[i],
        lat: obj.lat[i],
        lng: obj.lng[i],
        surge: obj.surge[i]