1

I need to compare two identical objects (the second one has one property more than other).

I create this snippet which puts all properties of an object into a new object without nesting them:

function getAllObjectProperties(source) {
  var result = {};
  function getProperties(object) {
    for (var property in object) {
      if (typeof object[property] === 'object') getProperties(object[property]); 
      else result[property] = object[property];
    }
  }
  getProperties(source);
  return result;
}

The comparing function should be like this:

updateObjectProperties: function(source, target) {
    var temp_object = self.getAllObjectProperties(source);
    for (var property in temp_object) {
        if (target.hasOwnProperty(property)) {
            // target_property_of_target_element = temp_object[property];
        }
        else {
            // target_object gains new property (property nesting must be preserved)
        }
    }
}

How can I do? Is it possible?

Pang
  • 9,564
  • 146
  • 81
  • 122
Giacomo
  • 37
  • 1
  • 7

2 Answers2

1

When you copy the properties of one object to another you can use something called a deep copy or a shallow copy. In the shallow copy, the target object is going to have references to properties of the source object, meaning that changes in objects of the target are going to change objects in the source.

Here is an example of shallow copy:

var source = {a: 0, b: {c: 2, d: 3}},
    target = {a: 1};

function union(target, source) {
    Object.keys(source).filter(function (key) {
        return !target.hasOwnProperty(key);
    }).forEach(function (key) {
        target[key] = source[key];
    });
}

union(target, source);

console.log(target);

To do a deep copy you can use JSON, but that only works if the properties can be expressed in JSON. Here is the union function performing a deep copy.

function union(target, source) {
    Object.keys(source).filter(function (key) {
        return !target.hasOwnProperty(key);
    }).forEach(function (key) {
        target[key] = JSON.parse(JSON.stringify(source[key]));
    });
}
Rodrigo5244
  • 5,145
  • 2
  • 25
  • 36
  • I tried the function but I had errors in my specific case. I'm not so good to understand why, pity I like this approach. Objects in my case are json files. – Giacomo Oct 12 '15 at 07:23
1

You can merge objects. You can add conditional operators if you only want the objects merged under certain conditions.

research for this answer: How can I merge properties of two JavaScript objects dynamically?

Code:

  var mergeObj =  function (obj1, obj2) {
    var obj3 = {};
    for (var attrname in obj1) {
        obj3[attrname] = obj1[attrname];
    }
    for (var attrname in obj2) {
        obj3[attrname] = obj2[attrname];
    }
    return obj3;
}

JS Fiddle

https://jsfiddle.net/chrislewispac/8fthog46/

Community
  • 1
  • 1
Chris L
  • 1,051
  • 1
  • 7
  • 20