Sean
Sean

Reputation: 15144

Angular .extend changing object reference

I have an array of objects:

var items = [{id:1,name:'one'},{id:2,name:'two'}];

I then select one and make a copy:

var item = items[0];
var copy = angular.copy(item);

I then change a property:

item.name = 'changed';

What are the values?

console.log(item.name);     // changed
console.log(items[0].name); // changed

The array element is the same object reference as the item, so the properties are the same.

Now I want to undo the change from the copy:

item = angular.extend(copy);

What are the values?

console.log(item.name);     // one
console.log(items[0].name); // changed

By using .extend, I thought I was setting the properties on the item, and NOT changing the object reference, so I was expecting the array item to still be the same object reference as the item and thus to have the same name property, i.e. 'one'.

What went wrong?

Upvotes: 0

Views: 1066

Answers (2)

tanmay
tanmay

Reputation: 7911

If you have a look at angular.extend, it takes two args, dst and src. It will copy src object to dst, right? So, in this case, instead of doing following thing,

item = angular.extend(copy);

What you should be doing is,

item = angular.extend(items, copy)[0];

Here's code snippet:

var app = angular.module('myapp', []);

app.controller('MainCtrl', function($scope) {
  var items = [{
    id: 1,
    name: 'one'
  }, {
    id: 2,
    name: 'two'
  }];

  var item = items[0];
  
  var copy = angular.copy(item);
  item.name = 'changed';

  console.log(item.name); // changed
  console.log(items[0].name); // changed
  console.log("===================");

  item = angular.extend(items, copy)[0];

  console.log(item.name); // one? (nope!)
  console.log(items[0].name); // changed
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp" ng-controller="MainCtrl">
</div>

Upvotes: 1

Sean
Sean

Reputation: 15144

I think what I'm needing is:

Object.assign(item, copy);

Upvotes: 0

Related Questions