[Javascript] Build lodash.merge from Scratch
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.
function mergeJSON(obj, ...sources) { for (let source of sources) { for (let key in source) { if (source[key] == null) { continue; } obj[key] = replaceValue(obj[key], source[key]); } } return obj; } function replaceValue(value, newValue) { if (Array.isArray(value) && Array.isArray(newValue)) { return newValue.map((val, i) => { return replaceValue(value[i], val) }); } if (isObject(value) && isObject(newValue)) { return mergeJSON(value, newValue); } return newValue; } function isObject(obj) { return obj && obj.constructor === Object; } module.exports = { mergeJSON };
index.js
import { mergeJSON } from "./merge"; const user1 = { name: "Joe", age: 33, links: { blog: "blog link", facebook: "facebook link" }, interests: ["gaming"] }; const user2 = { name: "Joe", age: 22, links: { twitter: "twitter link", blog: "another blog", facebook: null }, interests: ["code"], extra: false }; const user3 = { name: "Joe", age: 32, interests: ["gaming", "travling"] }; const res = mergeJSON(user1, user2, user3); console.log("mergeJSON", res);
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2020-04-11 [RxJS] Extend Promises by Adding Custom Behavior
2019-04-11 [Algorithm] Binary tree: Level Order Traversal
2019-04-11 [SSH] Intro to SSH command
2018-04-11 [Tailwind] Extending Tailwind with Responsive Custom Utility Classes
2018-04-11 [Tailwind] Control What Variations are Generated for Each Utility Class Module in Tailwind
2016-04-11 [RxJS] Creation operator: of()