Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
41
rated 0 times [  43] [ 2]  / answers: 1 / hits: 6236  / 10 Years ago, sun, april 20, 2014, 12:00:00

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 data array of integers with uniform length for each: gdp, income, uRate.



GOAL: Combine these into a single object for each city:



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


I've tried variations of the following.



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


Or, if city matches, add the metric (either 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 a similar example using $.extend() with jQuery: How to merge two object values by keys, but I am not using jQuery and would prefer either lodash, d3.js or vanilla js solution.



Thank You.


More From » sorting

 Answers
11

Using lodash _.merge will satisfy the original question:



Given 3 objects:



var gdp = {
city: city,
gdp: [],
};

var income = {
city: city,
income: [],
};

var uRate = {
city: city,
uRate: [],
};


Then bring in lodash and do:



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


and the result is as desired:



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


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


[#45876] Friday, April 18, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kaylea

Total Points: 459
Total Questions: 97
Total Answers: 106

Location: Denmark
Member since Wed, Aug 26, 2020
4 Years ago
;