close

How to deep merge instead of shallow merge?

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How to deep merge instead of shallow merge? in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

How to deep merge instead of shallow merge ?

  1. How to deep merge instead of shallow merge ?

    deep merge instead of shallow merge We can use $.extend(true,object1,object2) for deep merging. Value true denotes merge two objects recursively, modifying the first.

  2. deep merge instead of shallow merge

    deep merge instead of shallow merge We can use $.extend(true,object1,object2) for deep merging. Value true denotes merge two objects recursively, modifying the first.

Method 1

Here is an immutable (does not modify the inputs) version of @Salakar’s answer. Useful if you’re doing functional programming type stuff.

export function isObject(item) {
  return (item && typeof item === 'object' && !Array.isArray(item));
}

export default function mergeDeep(target, source) {
  let output = Object.assign({}, target);
  if (isObject(target) && isObject(source)) {
    Object.keys(source).forEach(key => {
      if (isObject(source[key])) {
        if (!(key in target))
          Object.assign(output, { [key]: source[key] });
        else
          output[key] = mergeDeep(target[key], source[key]);
      } else {
        Object.assign(output, { [key]: source[key] });
      }
    });
  }
  return output;
}

Method 2

We can use $.extend(true,object1,object2) for deep merging. Value true denotes merge two objects recursively, modifying the first.

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment