Merge two objects without removing the original properties

I have two objects namely Object1 and Object2.

var Object1 = {    
     child1: [{name: "google", check: false}, 
       {name: "yahoo", check: false}, {name: "msn", check: false}],
     child2: [{name: "google", check: false}, {name: "yahoo", check: false}],        
};

var Object2 = {
    child1: [{name: "google", check: true}, {name: "yahoo", check: true}],
};

I would like to replace the Object2 Child1 array with Object1 Child1 array but not removing the properties which are not there in Object2.

const NewObject = Object.assign({}, Object1, Object2)

The above code gives me NewObject with only Object2. The Final output i am looking at is where the check true property of second object is replaced in primary one.

var Object3 = {    
         child1: [{name: "google", check: true}, 
           {name: "yahoo", check: true}, {name: "msn", check: false}],
         child2: [{name: "google", check: false}, {name: "yahoo", check: false}],        
};      

Most of the answer here are based upon the fact that the elements in attributes child1 have the same index for the same name. If this is not the case let me offer you an alternative. This solution matches the elements inside child1 based on name and not array index.

var Object1 = {child1: [{name: "google", check: false}, {name: "yahoo", check: false}, {name: "msn", check: false}], child2: [{name: "google", check: false}, {name: "yahoo", check: false}]};
var Object2 = {child1: [{name: "yahoo", check: true}, {name: "google", check: true}]};
//                                ^                             ^
// I swapped the elements of Object2.child1 around to better show the
// intention of this specific solution.

function customAssign(obj1, obj2) {
  var result = {};

  // based on the fact that obj2 has a subset of keys of obj1
  Object.getOwnPropertyNames(obj1).forEach(key => {
    var attr1 = obj1[key], 
        attr2 = obj2[key], 
        itemLookup = {};

    if (Array.isArray(attr1) && Array.isArray(attr2)) {
      // based on the fact that the collection of an attribute
      // of obj2 a subset of the same attribue at obj1
      attr2.forEach(item => itemLookup[item.name] = item);
      result[key] = attr1.map(item1 => {
        var item2 = itemLookup[item1.name];
        if (item2 && item2.check) return item2;
        return item1;
      });
    } else {
      result[key] = attr2 || attr1;
    }
  });

  return result;
}

console.log(
  customAssign(Object1, Object2)
);

How to Merge Objects in JavaScript, Summary: in this tutorial, you will learn how to merge two or more JavaScript objects To merge objects into a new one that has all properties of the merged objects, you a property that references to another object, the property of the original object and YesNo. Previous 3 Ways to Check If a Property Exists in an Object. If both objects have a property with the same name, then the second object property overwrites the first. The best solution in this case is to use Lodash and its merge() method, which will perform a deeper merge, recursively merging object properties and arrays. See the documentation for it on the Lodash docs.

I think the merge function from Lodash is what you are looking for. Or you can build your own function for merging object recursively, but the end result is going to be something very similar to what Lodash has achieved.

How to merge properties of two JavaScript objects dynamically , How to compare two JavaScript array objects using jQuery/JavaScript ? JavaScript | Object Properties � JavaScript TypeError - "X" has no� I needed a function to merge two objects together into one object. I liked it to be generic so I could merge all types of objects. The function is only copy root and child properties.

You are almost there, just use for..in to iterate Object1 and check if Object2 has the same key. If it has same key like child1 then use Object.assign. Note in Object.assign the value of common keys will be updated according to the order of the objects. For example in Object.assign({}, Object1[keys], Object2[keys]) it will create a new object with keys and values from both Object1 & Object2 , but if there is a common key between these two then values of keys in Object2 will update the same key in Object1

var Object1 = {
  child1: [{
      name: "google",
      check: false
    },
    {
      name: "yahoo",
      check: false
    }, {
      name: "msn",
      check: false
    }
  ],
  child2: [{
    name: "google",
    check: false
  }, {
    name: "yahoo",
    check: false
  }],
};

var Object2 = {
  child1: [{
    name: "google",
    check: true
  }, {
    name: "yahoo",
    check: true
  }],
};
let Object3 = {};

for (let keys in Object1) {
  if (Object2.hasOwnProperty(keys)) {
    Object3[keys] = Object.assign({}, Object1[keys], Object2[keys])
  } else {
    Object3[keys] = Object.assign({}, Object1[keys])
  }
}
console.log(Object3)

jQuery.extend(), Description: Merge the contents of two or more objects together into the first object. When two or more object arguments are supplied to $.extend() , properties If, however, you want to preserve both of the original objects, you can do so Merge defaults and options, without modifying the defaults. Removed � Selectors. How to merge properties of two JavaScript objects dynamically? Using Spread Operator: Spread operator allows an iterable to expand in places where 0+ arguments are expected. It is mostly used in the variable array where there is more than 1 values are expected.

Use merge function of lodash,

var Object1 = {    
     child1: [{name: "google", check: false}, 
       {name: "yahoo", check: false}, {name: "msn", check: false}],
     child2: [{name: "google", check: false}, {name: "yahoo", check: false}],        
};

var Object2 = {
    child1: [{name: "google", check: true}, {name: "yahoo", check: true}],
};

_.merge(Object1, Object2);
console.log(Object1);

jsfiddle

jQuery.merge(), )Returns: Array. Description: Merge the contents of two arrays together into the first array. It alters the length and numeric index properties of the first object to include items from the second. If you need the original first array, make a copy of it before calling $.merge() . Fortunately jQuery Object � Removed � Selectors. I have an object model MyObject with various properties. At one point, I have two instances of these MyObject: instance A and instance B. I'd like to copy and replace the properties in instance A with those of instance B if instance B has non-null values.

You can both use lodash or using spread operator, you can do something like this:

var Object3 = {
    child1: [...Object2.child1],
    child2: [...Object1.child2],
};

How to merge objects in JavaScript | by Prashant Yadav, Learn how to merge two or more objects in JavaScript. In shallow merge only the properties owned by the object will be merged, it will not� Sometimes it's easier to model several objects and then merge them together. Here's how to add, subtract, and join objects in Blender 2.8.

Documentation, The `_.property` iteratee shorthand. _.differenceBy([{ 'x': 2 } objects for ['barney', 'fred']. // The `_. Note: Unlike _.without , this method mutates array . Use _. remove to This method is like _.pull except that it accepts an array of values to remove. Note: Unlike return what + ' ' + _.initial(names).join(', ') +. (_.size( names) >� This is a feature in Web Intelligence which allows linking of two or more data providers( queries). Basically we merge objects from two or more queries in one webi report, so that we can use them in same block. Mandatory condition to merge objects is to have same data type. For eg. See below tables , coming from two different queries in webi

Copying and extending Objects in javaScript - DEV, 2) Extending Objects Changing a property value from the original object or property value from the shallow copy object it will affect each other. validate: true, name: "bar" }; // Merge defaults and options, without modifying� The \ArrayObject class has the possibility to exchange the current array to disconnect the original reference. To do so, it comes with two handy methods: exchangeArray() and getArrayCopy(). The rest is plain simple array_merge() of the provided object with the ArrayObjects public properties:

angular.merge, This function is deprecated, but will not be removed in the 1.x lifecycle. You can specify multiple src objects. If you want to preserve original objects, you can do so by passing an empty object as the target: var Unlike extend(), merge() recursively descends into object properties of source objects, performing a deep copy. Merge collections without duplicates in C#. Posted by Jonas Elfström Thu, 18 Oct 2012 21:28:00 GMT. Your task is to merge two lists of objects. The resulting collection should be without duplicates, based on a certain property on the objects. The lists are populated with very simple Person objects.

Comments
  • Object.assign() only performs a shallow copy. For more intricate merging, you'll need to write your own function.
  • From the Object.assign documentation. "Primitives will be wrapped, null and undefined will be ignored." meaning that the if-statement can be removed. Furthermore it might be worth noting that the array is merged based on element position and not based on element name. If arrays are always delivered in the correct order this might not be an issue though.
  • @3limin4t0r hey thaks for sharing , i overlooked that if part. Thanks for bringing it up