Combine two javascript objects if the key is either lodash, vanilla js, or d3

I have 3 similar javascript objects.

var gdp = { "city": city, "gdp": [], }; var income = { "city": city, "income": [], }; var uRate = { "city": city, "uRate": [], }; 

Where I have many cities (n = 28), and [] is my array of integer data with the same length for each: gdp, income, uRate .

PURPOSE: Combine them into one object for each city:

 var finalData = { "city": city, "gdp": [], "income": [], "uRate": [] } 

I tried the options for the following.

 if ( ObjA.city == ObjB.city ) { Obj.city.metric = this.metric] }; 

Or, if the city ​​matches , add a label (gdp, income, or uRate) to the finalData object.

 cities.forEach(function ( city ) { var metrics = ['gdp', 'income', 'uRate']; metrics.forEach(function ( metric ) { if ( metric.city == city ) { // edit: removed i var finalData = { "city": city, "gdp": [], "income": [], "uRate": [] }; } }) return finalData; // edit: moved this per suggestion }; 

Here is an example using $ .extend () with jQuery: How to combine two values ​​of an object by keys , but I do not use jQuery and prefer either lodash, d3.js or vanilla js.

Thank.

+1
javascript object sorting lodash
Apr 20 '14 at 18:35
source share
2 answers

Using lodash _.merge satisfy the original question:

Given 3 objects:

 var gdp = { "city": city, "gdp": [], }; var income = { "city": city, "income": [], }; var uRate = { "city": city, "uRate": [], }; 

Then enter lodash and do:

 var finalData = _.merge(gdp, income, uRate); 

and the result will be as required:

 { "city": city, "gdp": [], "income": [], "uRate": [] } 

Working solution here: http://jsfiddle.net/e99KQ/3/

+4
Apr 20 '14 at 20:33
source share
β€” -

For those who land here from Google, it is now quite easy to do this with vanilla JS using Object.assign () .

This is a zero dependency equivalent to the result in the accepted answer:

 Object.assign({}, gdp, income, uRate); 

Note that this will not work in IE, but it will work in Edge. polyfill is not too heavy.

Working solution at https://jsfiddle.net/bLhk6x6a/1/

+2
Mar 27 '17 at 19:21
source share



All Articles