2

I have 2 javascript objects: obj_a and obj_b:

var obj_a = {'p1':{x:100, y:200, z:100}, 'p2':{x:100, y:100, z:300}};
var obj_b = {'p1':{x:100, y:200}, 'p2':{x:100, y:100}};

I'm trying to copy only "x and y values" of obj_b to obj_a if they're different. For example,

if obj_b = {'p1':{x:200, y:200}, 'p2':{x:300, y:400}};,

final obj_a will be obj_a = {'p1':{x:200, y:200, z:100}, 'p2':{x:300, y:400, z:300}};. completely ignoring the property "z" of obj_a.

So, I've written the following:

function isDifferent(a, b) {
    var aProps = Object.getOwnPropertyNames(a);
    var bProps = Object.getOwnPropertyNames(b);
    for (var i = 0; i < bProps.length; i++) {
        var propName = bProps[i];
         if (a[propName] != b[propName]) {
            return true;
        }
    }
    return false;
}
for (var prop in obj_b){
    if(isDifferent(obj_a[prop], obj_b[prop]){
        var bProps = Object.getOwnPropertyNames(obj_b[prop]);
        for (var i = 0; i < bProps.length; i++){
            var propName = bProps[i];
            obj_a[prop].propName = obj_b[prop].propName;
        }
    }
}

But there's a problem in copying using obj_a[prop].propName since I only get undefined when I console.log(obj_a[prop].propName);. When I tried console.log(obj_a[p1].x);, the output is the old value: "200". Can somebody enlighten me?

Black Snow
  • 43
  • 7

2 Answers2

3

If you're referencing an object property by a name stored in a variable, you need to use the bracket notation. In your case, instead of

var propName = bProps[i];
obj_a[prop].propName = obj_b[prop].propName;

use

var propName = bProps[i];
obj_a[prop][propName] = obj_b[prop][propName];
doldt
  • 4,466
  • 3
  • 21
  • 36
2

You should use obj_a[prop][propName]. object[prop].propName is the same as object[prop]["propName"] which means that it'll search for the property whose name is "propName" literally.

Therefore, obj_a[p1].x will return the value that you expect but obj_a[p1].propName will be undefined since your obj_a[p1] doesn't have a property name "propName".

What you want is to treat "propName" as a "string variable" not as a "string literal".

J.Jay
  • 249
  • 1
  • 4
  • 18