Fully Basic Javascript Help Question

In the Javascript console, the following:

var a = {'foo': []}; var b = {}; for (var key in a) { b[key] = a[key]; } a['foo'].push(1); console.log(b); 

Productivity:

Object foo=[1]

I want to make a copy by the value in b of each array for each key in a. Is there an easier way?

+6
javascript deep-copy
source share
4 answers

This is called Deep Copy . Examples can be found in:

+3
source share

You can create a β€œclone” function that creates a new object based on the original constructor object, and then clone the original properties of the object as well, if they are objects:

 function clone(obj){ if(typeof(obj) != 'object' && obj != null) return obj; // return the value itself if isn't an object // or null, since typeof null == 'object'; var temp = new obj.constructor(); for(var key in obj) temp[key] = clone(obj[key]); return temp; } var a = {'foo': []}; var b = clone(a); a['foo'].push(1); console.log(b); // Object foo=[0] 
+4
source share

A simple way:

 var a = {'foo': []}; var b = a; a['foo'].push(1); console.log(b); 

The conclusion is the same.

Edit:

 var a = {'foo': []}; var b = {}; for (var key in a) { if (a.hasOwnProperty(key)) { b[key] = []; for (var i = 0; i < a[key].length; i += 1) { b[key][i] = a[key][i]; } } } a['foo'].push(1); console.log(b); 
0
source share

Since this will add support for deep copying arrays to your code:

 var a = {'foo': []}; var b = {}; for (var key in a) { if (Object.prototype.toString.call(b[key]) === "[object Array]") { b[key] = a[key].slice(0); } else { b[key] = a[key]; } } a['foo'].push(1); console.log(b); 
0
source share

All Articles