1. 2
    Deep Merge Objects in JavaScript with Spread, Lodash, and Deepmerge
    4m 22s

Deep Merge Objects in JavaScript with Spread, Lodash, and Deepmerge

Chris Achard
InstructorChris Achard

Share this video with your friends

Send Tweet

If you are merging two objects that contain other objects or arrays, then you probably want to deeply merge those objects, instead of just shallow merging them. In this lesson, we'll look at three different ways to deeply merge objects, depending on what you want to accomplish: using the spread operator, using lodash's merge function, or using the deepmerge npm library.

Jonathan Farber
Jonathan Farber
~ a year ago

Thank you for that clarification regarding merge methods, I was wondering, if lodash only deep merges at the depth of one level, would the array flat() or even flatMap() methods help in achieving the same as deepmerge package? and secondly, if I would want to merge/copy only implicit properties from a given large object, how would I perform that?

Chris Achard
Chris Achardinstructor
~ a year ago

The real problem I was trying to show with lodash is that it treads arrays as objects, so you can't control how they get merged. I think that means that using flat or flatmap won't fix the issue with lodash (unless you had something specific in mind - do you have a code example that might work?)

For pulling out only some properties from each, the spread operator is probably your best bet - you can pull just the values you want; or you could do something like a deepmerge into a new object, and then make a second new object that just pulls out the keys from that new object that you want in your final object.

Jonathan Farber
Jonathan Farber
~ a year ago

Hi Chris, sorry, your right I didn't explain myself right, let me be a little more precise - For example: when receiving data from an API endpoint as a JSON Object with nested arrays. for instance, weather current conditions endpoint, so in this case, in order to parse only the relevant properties of the data object (i.e, not the entire object, let say only the temperature field in this case).

for illustration, I'll do my best to mock this out (don't judge me too hard, im still green behind the ears 🤓)

"Data": [
  {
    "DateTime": {
	  "DateString": "2020-05-11T20:50:40.356Z",
	  "WeatherText": "Clear"
	  "WeatherIcon": 6
	},
	"HasPrecipitation": false,
	"PrecipitationType": null,
	"Temperature": {
      "Metric": {
        "Value": 20,
        "Unit": "C"
      },
      "Imperial": {
        "Value": 68,
        "Unit": "F"
      }
  	}
  }
 ]

so given this response, what i would do to resolve this would be, to create a function that checks:

  • if the data is an array or object.
  • then feed the data to the parser function in order to parse only relevant data property fields.

for example something like this:

const isArrayOrObject = (jsonData) => {
  let result = jsonData;
  if (Array.isArray(result.data)) {
    return result.data.map((result) => currentConditionsReducer(result));
  } else {
    return currentConditionsReducer(result.data);
  }
};
 
 export const currentConditionsReducer = (result, language) => {
  return {
    currentDate: dateFromString(result.DateString, language),
    weatherPhrase: result.WeatherText,
    icon: iconUrlResolver(result.WeatherIcon),
    temperature: result.Temperature.Imperial.Value,
	};
};

const dateFromString = (value, language) => {
  return new Date(value).toLocaleDateString(language, {
    day: "2-digit",
    month: "2-digit",
    year: "numeric",
  });

now back to my first question from earlier, i feel like there must be a better way to perform this then hard coding the values i am interested in parsing?

thank you for your patience so far... I hope i wasn't too hard to understand 😅

Jonathan Farber
Jonathan Farber
~ a year ago

Sorry my indentations moved due to copy/paste

Chris Achard
Chris Achardinstructor
~ a year ago

Hm - yeah, when data gets complex like that (especially when you have to check if it's an array or object, etc), then yeah, I'm not sure there's a better way then just doing it by hand.

The code you have there looks straightforward enough - not sure I could get it much shorter / simpler. So I think you've done about what I would do there :)

Jonathan Farber
Jonathan Farber
~ a year ago

Thank you, wow... i truly thought that I was going about this the wrong way, I don't know if you are familiar with Object Proxy methods like Object.fromEntries but i strongly think that there is a possibility to create a dynamic function which can map over any given data and merge the values, where I could use a single config enumeration to filter the relevant properties.

anyways, thank you so much for the input much appreciated, and if i find a better approach I'll be sure to update.