Build lodash.merge from Scratch

Jamund Ferguson
InstructorJamund Ferguson
Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 3 years ago

This lesson will demonstrate how to recreate a simplified version of the popular lodash.merge method from scratch.

First we'll create a test file with two objects that we want to merge together and demonstrate the output after running them through lodash.merge , then we'll go about creating our own version of the function.

Our initial version will support only one source object to merge in, and will support only the subset of JavaScript syntax supported by the JSON spec, including the following types:

  • boolean, number, string
  • object literal
  • array

After getting basic types to merge we'll show off two methods for merging arrays, either using concat or recursively going through the children and merging them.

Finally we'll build our own isObject function to check for object literals and recursively apply our mergeJSON function to any object literals in our source object.

And last we'll add support for multiple source objects to be merged in using a for...of loop.

Note

The mergeJSON method we create approximates the lodash.merge functionality but does not seek to replace it. It may be useful for some use cases, but primarily it's meant to be a tool for understanding how to merge objects with recursion.

egghead
egghead
~ 7 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today