0

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?

hlfcoding
  • 2,532
  • 1
  • 21
  • 25
ranjeet8082
  • 2,269
  • 1
  • 18
  • 25
  • 1
    this is related to *object cloning*, try searching for that. – King King Oct 28 '14 at 06:00
  • This post also might be relevant in explaining how objects are handled and how to copy them elegantly in javascript - http://stackoverflow.com/questions/728360/most-elegant-way-to-clone-a-javascript-object – Vivek Pradhan Oct 28 '14 at 06:04

3 Answers3

1

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()

Amitesh
  • 1,507
  • 1
  • 11
  • 19
0

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); 
Community
  • 1
  • 1
Shadi
  • 2,236
  • 2
  • 22
  • 22
0

You can use

var b = JSON.parse(JSON.stringify(a));

https://stackoverflow.com/a/4591639/1623259

Community
  • 1
  • 1
Uttam K C
  • 204
  • 2
  • 4