Object.assign removing existing property

Object.assign can't manage nested objects. You have to loop through the properties of your object.

The code below manage your case but if you want to work with more nested objects, do the proceess recursively

var o1 = { "status":"", "app":{"version":"1.3.1.91","latest_version":"1.3.1.91"} };
var o2 = { "status":"listening", "app":{"latest_version":"1.3.2.879"} };

var output = {};
Object.keys(o2).forEach(key => {
    if (o2[key] instanceof Object) {
        output[key] = Object.assign({}, o1[key], o2[key]);
    } else {
        output[key] = o2[key];
    }
});

console.log(output);

Properties in the target object will be overwritten by properties in the sources if they have the same key. Later sources' properties will similarly overwrite earlier ones.

The Object.assign() method only copies enumerable and own properties from a source object to a target object. It uses [[Get]] on the source and [[Set]] on the target, so it will invoke getters and setters. Therefore it assigns properties versus just copying or defining new properties.

states MDN. If you are down to use jQuery, this task can be simply done by $.extend() (read more on api.jquery.com): Otherwise, you are very likely to write something like @Faly's answer.

var o1 = { "status":"", "app":{"version":"1.3.1.91","latest_version":"1.3.1.91"} }
var o2 = { "status":"listening", "app":{"latest_version":"1.3.2.879"} }

console.log($.extend(true, {}, o1, o2));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Tags:

Javascript