[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-05-19永别了,微服务架构!
- 2024-05-15鸿蒙生态设备数量超8亿台
- 2024-05-13TiDB + ES:转转业财系统亿级数据存储优化实践
- 2024-05-09“2024鸿蒙零基础快速实战-仿抖音App开发(ArkTS版)”实战课程已上线
- 2024-05-09聊聊如何通过arthas-tunnel-server来远程管理所有需要arthas监控的应用
- 2024-05-09log4j2这么配就对了
- 2024-05-09nginx修改Content-Type
- 2024-05-09Redis多数据源,看这篇就够了
- 2024-05-09Google Chrome驱动程序 124.0.6367.62(正式版本)去哪下载?
- 2024-05-09有没有大佬知道这种数据应该怎么抓取呀?