Merge Two Javascript Objects If Key Is Equal With 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,
Solution 1:
To anyone landing here from Google, it's now pretty 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 won't work in IE, but will work in Edge. The polyfill isn't too heavy, though.
Working solution at https://jsfiddle.net/bLhk6x6a/1/
Solution 2:
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/
Post a Comment for "Merge Two Javascript Objects If Key Is Equal With Either Lodash, Vanilla Js, Or D3"