The following in a Javascript console:
var a = {'foo': []};
var b = {};
for (var key in a) {
b[key] = a[key];
}
a['foo'].push(1);
console.log(b);
Yields:
Object foo=[1]
I want to make a copy by value in b of each array for each key in a. Is there an easier way?
JavaScript is a popular web scripting language and is used for client-side and server-side development. The JavaScript code can be inserted into HTML pages that can be understood and executed by web browsers while also supporting object-oriented programming abilities.
You could make a "clone" function that creates a new object, based on the original object constructor, and then clone that original object properties also 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]
This is called Deep Copy. You can find examples in:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With