From 5f41e6076daab49f6fefe76979837d3acd13a03a Mon Sep 17 00:00:00 2001 From: James Lu Date: Wed, 12 Apr 2023 10:40:59 +0800 Subject: [PATCH] Refactor nested object merge using Immutable-js The commit refactors the code to use the `mergeDeepWith` function of `Im mutable-js` to keep the nested object original structure. --- note.md | 75 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/note.md b/note.md index 352519c..58a30b7 100644 --- a/note.md +++ b/note.md @@ -4319,3 +4319,78 @@ const refreshPage = async () => { --- +## 155. Using function `mergeDeepWith` of `Immutable-js` to keep nested object original structure. + +```js +const { mergeDeepWith } = require(’immutable@4.3.0‘) + +const original = { + x: { + y: 123, + z: { + a: { + b: null + } + } + }, + user: { + menu: { + codes: [] + }, + info: { + name: null, + age: null + } + } +} + +const responseData = { + x: { + y: 123, + z: null + }, + user: { + menu: null, + info: { + name: ’James‘, + age: 37 + } + } +} + +const result = mergeDeepWith( + (oldVal, newVal) => { + if ([null, ’‘, undefined].includes(newVal)) { + return oldVal + } + + return newVal + }, + original, + responseData +) + +console.error(result) +/** +* x: { + y: 123, + z: { + a: { + b: null + } + } +}, +user: { + menu: { + codes: [] + }, + info: { + name: ’James‘, + age: 37 + } +} +*/ +``` + +— +