0

I have problem with returning the value of object property

function Obj() {
this.objects =
        [
            {
                id: 0,
                values: {
                    x: 10,
                    y: 10
                }
            },
            {
                id: 1,
                values: {
                    x: 15,
                    y: 20
                }
            }
        ];
    }
Obj.prototype.getOjects = function() {
    return this.objects;
};
Obj.prototype.getModifiedOjects = function() {
    var i, obj;
    obj = this.getOjects();

    for(i=0; i<obj.length; i++ ){
        obj[i].values.x *= 2;
        obj[i].values.y *= 2;
    }
    return obj;
};

var obj = new Obj(), modifiedObjects;
console.log(obj.getOjects()); // value of 0 => {x => 10, y: 10}, 1 => {x => 15, y: 30}
modifiedObjects = obj.getModifiedOjects(); // Do something with mofified objects
console.log(obj.getOjects()); // value of 0 => {x => 20, y: 20}, 1 => {x => 30, y: 40}

When I call the getModifiedOjects function, also change the values of objects property.

How to make the getOjects function to not return object property by reference?

Thanks.

Igor
  • 171
  • 1
  • 8
  • instead of returning the actual array. you could return a new object with just ids or the properties that you want to expose – Prabhu Murthy Aug 21 '14 at 08:02

2 Answers2

0

To return a copy of the objects instead of the objects you need to create the copies:

Obj.prototype.getModifiedOjects = function() {
  var i, obj, result;
  obj = this.getOjects();
  result = [];
  for (i = 0; i < obj.length; i++) {
    result.push({
      id: obj[i].id,
      values: {
        x: obj[i].values.x * 2,
        y: obj[i].values.y * 2
      }
    });
  }
  return result;
};
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

Objects in Javascript are passed around by reference (as you've discovered) so getObjects() just returns a pointer to the same object that is internal to obj. The only way to make getObjects() return something completely different that can be modified without changing what obj has inside it is to make an explicit copy of the object.

Since your object has nested objects in it, you will have to make a "deep" copy so that everything is copied.

There are a variety of different ways to clone or copy your objects. Here are some references:

How do I correctly clone a JavaScript object?

What is the most efficient way to deep clone an object in JavaScript?

Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979