HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Join JSON objects on common property

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
objectsjoinpropertyjsoncommon

Problem

is there an easier/more efficient way to join two JSON objects on a common property than this? It's a GeoJSON file (basically an array of objects), and I want to pull in a property from another JSON file (array of objects) based on a common property, similar to a SQL SELECT a., b. FROM a LEFT JOIN b ON a.id = b.a_id

$.when(
    $.getJSON('https://data.phila.gov/resource/bbgf-pidf.geojson'),
    $.getJSON('https://data.phila.gov/resource/r24g-zx3n.json?%24select=count(*)%20as%20value%2C%20%3A%40computed_region_bbgf_pidf%20as%20label&%24group=%3A%40computed_region_bbgf_pidf&%24order=value%20desc')
).done(function(responseGeojson, responseData) {
    var data = responseData[0]
    var geojson = responseGeojson[0]

    // Create hash table for easy reference
    var dataHash = {}
    data.forEach(function(item) {
        if(item.label) dataHash[item.label] = item.value
    })

    // Add value from hash table to geojson properties
    geojson.features.forEach(function(item) {
        item.properties.incidents = +dataHash[item.properties._feature_id] || null 
    })

    console.log(geojson)
})

Solution

I notice a query on one of your urls. I suggest you use jQuery's $.param to construct the query cleanly.

For your first loop, you could use reduce instead of forEach to generate your hash. Additionally, you might want kill NaN early. You don't want to be carrying NaN in any data structure, otherwise you'll get some unexpected NaN in your code.

var dataHash = data.reduce(function(hash, item) {
  var value = +item.value
  hash[item.label] = isNaN(value) ? null : value;
  return hash;
}, {});

geojson.features.forEach(function(item) {
  item.properties.incidents = dataHash[item.properties._feature_id];
});


As for efficiency, I guess that's about it. You don't want to be nesting a lookup inside the other loop. Two separate loops is better then one nested inside another.

Code Snippets

var dataHash = data.reduce(function(hash, item) {
  var value = +item.value
  hash[item.label] = isNaN(value) ? null : value;
  return hash;
}, {});

geojson.features.forEach(function(item) {
  item.properties.incidents = dataHash[item.properties._feature_id];
});

Context

StackExchange Code Review Q#110473, answer score: 2

Revisions (0)

No revisions yet.