This question already has answers here:
What is the most efficient way to deep clone an object in JavaScript?
(67 answers)
Closed 8 years ago.
I created an object array with some values. Then I created another object array and initialized it with the first one. Then I pushed a value in 2nd array, and console logged both arrays. Both arrays had same value. Why is this happening and how can we stop this?
My Code:
var a = { "filters": [] }; // 1st object array
var keyValue = {};
// pushed 2 values in "a" array
keyValue["abc"] = "123";
a.filters.push(keyValue);
keyValue["def"] = "456";
a.filters.push(keyValue);
var b = a; // created another object array & initialized it with "a" array
var keyValue1 = {};
// pushed 1 value in "b" array
keyValue1["ghi"] = "789";
b.filters.push(keyValue1);
console.log(a);
console.log(b);
This prints same values for a and b.
How do I push values into 2nd array without updating 1st one?
Assignment such as var b = a for a object creates an object 'b' which references(just like pointer) the same location pointed by 'a', in general. You may find this link helpful.
However you can create/clone a new array with slice method. var b = a.slice()
You can use
var b = JSON.parse(JSON.stringify(a));
https://stackoverflow.com/a/4591639/1623259
Both are pointing to the same values in the memory when you say:
var b = a;
So if you change a, b will be affected and vice versa, you need to copy using a loop.
EDIT
use this line of code which I get from this post
var b= a.slice(0);
Related
This question already has answers here:
What is the most efficient way to deep clone an object in JavaScript?
(67 answers)
Closed 3 years ago.
I have one object
var a = {b:{c:{d:{e:1}}}}
I want to copy that object to another variable b, without passing a reference, so I try spread operator
var b = {...a}
It is not removing reference at a deep level, as I change the value in the object "a" it also changes the value in the object "b"
a.b.c.d.e = 2
console.log(b.b.c.d.e)
it give output 2 instead of 1
var a = {b:{c:{d:{e:1}}}};
var b = {...a};
a.b.c.d.e = 2;
console.log(b.b.c.d.e)
document.write(b.b.c.d.e)
How can I handle this issue
I've always done this to copy JSON objects. Works great IMO there may be a better way out there.
var a = {b:{c:{d:{e:1}}}};
var b = JSON.parse(JSON.stringify(a));
a.b.c.d.e = 2;
console.log(b.b.c.d.e)
document.write(b.b.c.d.e)
This question already has answers here:
Copy array by value
(39 answers)
Closed 5 years ago.
function myFunction() {
var a = {};
a.myArray = ["Saab", "Volvo", "BMW"];
var b=a.myArray;
b.push("Chevy");
alert(a.myArray);}
In this above function I have created an object "a" and created an array "myArray". Now I am copying that array in "b" and modifying array "b".But why is it changing a.myArray and how to avoid this?
Because you assigned the reference of that array. So you are actually referring the same array with different variable name.
If you want to seperate arrays
var b = a.slice();
Which gives you a new array with same values of your initial array.
slice()
The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.
This question already has answers here:
Why does Array.prototype.push return the new length instead of something more useful?
(6 answers)
Closed 4 months ago.
If I do
var a = [].push(undefined);
console.log(a);
it gives output as 1 even though undefined was pushed to the array. Any idea why?
You're testing it the wrong way. a is not defined as the array, as I think you suppose it to be. Try this:
var a = []
a.push(undefined);
console.log(a);
You are assigning the return value of push function to variable a. push returns the length of the array after pushing the current element in context. So, it returns 1 after pushing undefined in the array.
its pushing the length of array inside not the elements
example
var a = [].push(5,6,7,8);
console.log(a); //gives 4
Push returns the new length of the array, and thats what is stored in a
There was no explicit check has been done when assigning a new property to array object. Assigning a new property in the sense, setting 0,1,2..n properties with values, based on the length of the array.
Repeat, while items is not empty
Remove the first element from items and let E be the value of the element.
Let setStatus be Set(O, ToString(len), E, true).
ReturnIfAbrupt(setStatus).
Let len be len+1.
You can see it here. Step 8.
This question already has answers here:
Copy array by value
(39 answers)
Closed 9 years ago.
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?
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?
use new Array().
var arr = [{'name':'one','age':24},{'name':'two','age':21}];
var newArr=new Array(arr);
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.
This question already has answers here:
Copy array by value
(39 answers)
Closed 9 years ago.
It's really strange, I'm modifying one of the arrays and the other one gets modified! I found no way of making it work other than typing two times the array. What can I do?
function test(a,b,c,d)
{
this.a=a;
this.b=b;
this.c=c;
this.d=d;
}
var data0=data=[[1,2,3,4],[5,6,7,8]];
function construct(constructor,args)
{
function F(){return constructor.apply(this,args);}
F.prototype=constructor.prototype;
return new F();
}
for(var i=0,l=data.length;i<l;i++)
{
data[i]=construct(test,data[i]);
}
console.log(data0);
http://jsfiddle.net/mageek/3GNMC/2/
You are referencing the same items:
var data0=data=[[1,2,3,4],[5,6,7,8]];
(and as a side note - here data ends up on the global object as it isn't really declared, only data0 is)
If you want to generate two different arrays with identical items you can do this:
var data0 =[[1,2,3,4],[5,6,7,8]];
var data = [];
data = data.concat(data0);
or
data = data0.slice(0);
JavaScript will not copy arrays upon data0=data assignment, instead it will point both variables to the same object in memory. You need to actually clone the array fully, for example:
var data0 = data.slice(0);