underscore attribute join
by abenrob
JavaScript
function outputJSON(input) {
document.body.appendChild(document.createElement('pre'))
.innerHTML = JSON.stringify(input, null, 2);
}
var geo = [
{name:'north', coords: {x:0,y:1}},
{name:'east', coords: {x:1,y:0}},
{name:'south', coords: {x:0,y:11}},
{name:'west', coords: {x:-1,y:0}},
];
var attrs = [
{name:'east', score: 90, weather:'mild'},
{name:'south', score: 60, weather:'warm'},
{name:'west', score: 100, weather:'hot'},
];
var joiner = function(features,attributes,featurefield,attributefield){
var combi = [];
_.each(features, function(feature){
var matchObj = {};
matchObj[attributefield] = feature[featurefield];
var match = _.findWhere(attributes, matchObj);
var joined = _.extend({},feature,match);
combi.push(joined);
});
return combi;
};
outputJSON(joiner(geo,attrs,'name','name'));