var log = Helpers.log2Screen;
var format = new Helpers.Partial(Object.print, null, ' ');
Object.clone = cloneObj;
//a Fruit constructor
var Fruit = function (name){
this.name = name;
}
// create an Array of Fruit instances
var fruits = 'apple,banana,orange,kiwi,pear'.split(',')
.map(function(v) {return new Fruit(v);});
log('<h3>Cloning an Array of Objects</h3>');
// cloning by creating a new instance with old data
var fruits2 = fruits.map(function(v) {return new Fruit(v.name);});
// cloning by JSON
var fruits3 = fruits.map(function(v) {return JSON.parse(JSON.stringify(v));});
// original [fruits] should keep its values after this
fruits2[0].name = 'strange fruit';
//[fruits] and [fruits2] should keep their values after this
fruits3[0].name = 'pineapple';
// cloning by method map/cloneObj
var fruits4 = fruits.map(function(v) {return cloneObj(v);});
// fiddle around with fruits4 values (other fruits[x] keep their values)
fruits4[0] = {name: 'grapes', data: {price: 3, volume: 1}};
fruits4[1] = [1,2,3, {name: {pre: 'foo', last: 'bar', date: new Date()}}];
fruits4.push('a string value');
// and clone again, in one go, actually this is a fourth method, the
// using the cloneObj method you don't really need mapping
// Let's use the Obect.clone (static extension)
var fruits5 = Object.clone(fruits4);
// more fiddling: [fruits4] should keep its values
fruits5[0].name = 'tomatoe';
fruits5[0].data = null;
fruits5[1][3].name.test = 'abcd'.split('');
fruits5[1][3].name.date = new Date('2014/03/03 01:00');
fruits5.pop();
log( interpolate (
'fruits (the original one and only):<br>{fruits}<br><br>'+
'fruits2 (instances clone, modified):<br>{fruits2}<br><br>'+
'fruits3 (JSON clone, modified):<br>{fruits3}<br><br>'+
'fruits4 (`map/cloneObj` method clone, modified):<br>{fruits5}<br><br>'+
'fruits5 (`Object.clone` method clone (base fruits4), modified):<br>{fruits5}',
...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Get Fiddle Pages with PRO
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.