Wednesday 11 February 2015

Deep cloning objects in JavaScript

There are a lot of ways to clone objects in Javascript and here are two of them.

Using JSON library

var person = {
    name: "Jack",
    age: 21,
    address: {houseNumber: 11, postcode: 'BR3'}
};
 
var jill = (JSON.parse(JSON.stringify(person)));
jill.name = "Jill";
 
console.log(person);
console.log(jill);

Using jQuery’s $.extend()

var person = {
    name: "Jack",
    age: 21,
    address: {houseNumber: 11, postcode: 'BR3'}
};
 
var jill = $.extend(true, {}, person);
jill.name = "Jill";
 
console.log(person);
console.log(jill);

$.extend() method is a little slower than the JSON exploit, but that shouldn’t really be a problem when you’re only doing a few clones.

Click here to read more

No comments:

Post a Comment