1

I have objects in array as

var arr = [{'name':'one','age':24},{'name':'two','age':21}]

I have assigned this array to another variable var newVar = arr. Now I am changing value of an objects of newVar as newVar[0].age = 18, But change the value of object of newVar get reflected in arr(original data) as well. After change value in newVar, arr is

var arr = [{'name':'one','age':18},{'name':'two','age':21}]

I want original data should be independent of changing values of another variable holding same data. How can I get it with java script?

user3002180
  • 431
  • 6
  • 19

3 Answers3

2

Javascript handles objects by reference. If you have to change value in just a object you should "clone" it. This way there will be two different objects.

How to clone a object:

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

Community
  • 1
  • 1
Mardie
  • 1,663
  • 17
  • 27
0

use new Array().

var arr = [{'name':'one','age':24},{'name':'two','age':21}];
var newArr=new Array(arr);
Akhlesh
  • 2,389
  • 1
  • 16
  • 23
0

To copy an array you would use slice. Unfortunately slice makes only a shallow copy. To make a deep clone you can use map method + $.extend to clone object:

var arr = [{'name':'one','age':24},{'name':'two','age':21}]
var newArr = arr.map(function(el) {
    return $.extend({}, el);
});

newArr[0].name = 'TEST'
console.log(newArr[0].name, arr[0].name); // TEST one 

Or it can be event shorter using some javascript magic:

var newArr = arr.map($.extend.bind(null, {}));

Result is the same.

dfsq
  • 191,768
  • 25
  • 236
  • 258