[Javascript] Build lodash.merge from Scratch
2022/4/11 9:12:57
本文主要是介绍[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);
这篇关于[Javascript] Build lodash.merge from Scratch的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-23Springboot应用的多环境打包入门
- 2024-11-23Springboot应用的生产发布入门教程
- 2024-11-23Python编程入门指南
- 2024-11-23Java创业入门:从零开始的编程之旅
- 2024-11-23Java创业入门:新手必读的Java编程与创业指南
- 2024-11-23Java对接阿里云智能语音服务入门详解
- 2024-11-23Java对接阿里云智能语音服务入门教程
- 2024-11-23JAVA对接阿里云智能语音服务入门教程
- 2024-11-23Java副业入门:初学者的简单教程
- 2024-11-23JAVA副业入门:初学者的实战指南