简体   繁体   中英

Merge two arrays of objects based on key in javascript

I am working on merging geoJSON shapefiles with Census Data for web mapping.

Each element in each array has a GeoID, on which I would like to base the join.

I have successfully done this, but I wanted to see if anyone knows a better way, if there is anything I'm doing massively wrong.

The way I did it is by sorting each array with underscore based on the value of the GeoID property. I verified that each lined up with a test

//- Create array of features sorted by GeoID
var sortedShapes = _.sortBy(sfTracts.features, function(o) { return o.properties.GEOID10});
//- Create array of features (w/o shapes) by GeoID
var sortedData = _.sortBy(kidsInPov, function(o) { return o.GeoID} );

Then I used underscore .map() to combine them.

var count = 0;
var joinedData = _.map(sortedShapes, 
  function(o) {
  // add data desired from dataset
  o.properties.HD01_VD01 = sortedData[count].HD01_VD01;
  o.properties.HD01_VD02 = sortedData[count].HD01_VD02;
  o.properties.HD01_VD10 = sortedData[count].HD01_VD10;
  count++;
  return o
}
); 

Using the open source project jinqJs its very easy

See Fiddle

//Use jsJinq.com open source library
var list1= [{Location: 'NY', People: 200}, {Location: 'TX', People: 500}];
var list2= [{Location: 'NY', State: 'New York'}, {Location: 'TX', State: 'Texas'}]

var result = jinqJs().from(list1).join(list2).on('Location').select();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM