0

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?

2
  • naming is pretty confusing can you change var item all over Commented Mar 24, 2017 at 6:57
  • what end result do you want to achieve? Commented Mar 24, 2017 at 7:11

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

Comments

0

I think what I'm needing is:

Object.assign(item, copy);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.