Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

deep merge nested objects javascript

function clone(obj, isStrictlySafe = false) {
  /* Clones an object. First attempt is safe. If it errors (e.g. from a circular reference),
        'isStrictlySafe' determines if error is thrown or an unsafe clone is returned. */
  try {
    return JSON.parse(JSON.stringify(obj));
  } catch(err) {
    if (isStrictlySafe) { throw new Error(err) }
    console.warn(`Unsafe clone of object`, obj);
    return {...obj};
  }
}

function merge(target, source, {isMutatingOk = false, isStrictlySafe = false} = {}) {
  /* Returns a deep merge of source into target.
        Does not mutate target unless isMutatingOk = true. */
  target = isMutatingOk ? target : clone(target, isStrictlySafe);
  for (const [key, val] of Object.entries(source)) {
    if (val !== null && typeof val === `object`) {
      if (target[key] === undefined) {
        target[key] = new val.__proto__.constructor();
      }
      /* even where isMutatingOk = false, recursive calls only work on clones, so they can always
            safely mutate --- saves unnecessary cloning */
      target[key] = merge(target[key], val, {isMutatingOk: true, isStrictlySafe}); 
    } else {
      target[key] = val;
    }
  }
  return target;
}
Comment

PREVIOUS NEXT
Code Example
Javascript :: javascript json append array 
Javascript :: jquery dropdown select 
Javascript :: disable mixed content via javascript 
Javascript :: json limit nodejs 
Javascript :: mongodb sort objectid 
Javascript :: pushing element in array in javascript 
Javascript :: json update pytohn 
Javascript :: how to remove last element in js 
Javascript :: sequelize order with include 
Javascript :: javascript copy to clipboard 
Javascript :: javascript join list of string 
Javascript :: c# print object to json 
Javascript :: saving text in javascript 
Javascript :: redis set expire time node js 
Javascript :: Array Foreach Loop 
Javascript :: react bootstrap carousel caption placement top 
Javascript :: time js code 
Javascript :: javascript calculate percentage to pixel 
Javascript :: node promisify without err 
Javascript :: How to fetch API data using POST and GET in PHP 
Javascript :: get current location url javascript 
Javascript :: javascript convert object to querystring 
Javascript :: javascript hours minutes seconds 
Javascript :: react antd form disable submit button 
Javascript :: ajax current url 
Javascript :: ERROR Invariant Violation: requireNativeComponent: "RNCViewPager" was not found in the UIManager. 
Javascript :: dynamodb pagination nodejs 
Javascript :: jquery list all event listeners 
Javascript :: react download file from express res.download 
Javascript :: get first element in json array javascript 
ADD CONTENT
Topic
Content
Source link
Name
7+3 =