Gustav
Gustav

Reputation: 3576

angular.extend/merge object with array property

If I have these objects:

var first = {arr: ["foo"]};
var second = {arr: ["bar"]};

and then do

angular.extend(first, second);

this will be the state:

first.arr[0] //"bar"
first.arr === second.arr;//true

I want the first part, but i don't want the arrays to be the same reference.

When i try

angular.merge(first,second);

then nothing happens to the first.arr

first.arr[0]; //"foo

What is the proper way to extend first with the properties of second including arrays, but not having the same references?

Upvotes: 1

Views: 1406

Answers (1)

dfsq
dfsq

Reputation: 193271

You can merge both objects into new object:

angular.extend({}, first, second);

Then it should be what you want:

var first = {arr: ["foo"]};
var second = {arr: ["bar"]};

var result = angular.extend({}, first, second);

console.log(result.arr[0]); // bar
console.log(first.arr === second.arr); // false

Upvotes: 1

Related Questions