Well I suppose it depends on how deep the objects are and whether you have control over the organization of the objects. I believe for simple scenarios, you could do something along the following. Dunno if you qualify ES6 as Vanilla JS, so here's some ES5:
functionGarage(x,y,cars){// dimensions of the garage in feet, because America :/this.area={width:x,depth:y,}this.cars=cars;this.copy=function(garage){this.area.width=garage.area.width;this.area.depth=garage.area.depth;for(vari=0;i<garage.cars.length;i++){this.cars[i]=newCar(garage.cars[i].make,garage.cars[i].model);}};}functionCar(make,model){this.make=make;this.model=model;}(function(){varsomeGarage=newGarage(40.0,25.0,[newCar("Toyota","Camry"),newCar("Toyota","Prius"),newCar("Tesla","Model 3"),]);varotherGarage=newGarage(25.0,25.0,[newCar("Toyota","Camry"),]);// make the second garage a copy of the first, without using referencesotherGarage.copy(someGarage);// change the first garage to show that the garages aren't relatedsomeGarage.cars[2]=null;someGarage.area.width++;console.log("someGarage: ",someGarage);console.log("otherGarage: ",otherGarage);})();
Alternatively, if you have to handle dynamic objects of unknown dimensions, you could use a recursive function that uses Object.getOwnPropertyNames and the prototypes (someObject.__proto__) of those properties to handle the generation of fresh Objects for the properties of the destination object.
Well I suppose it depends on how deep the objects are and whether you have control over the organization of the objects. I believe for simple scenarios, you could do something along the following. Dunno if you qualify ES6 as Vanilla JS, so here's some ES5:
The output to the console:
Alternatively, if you have to handle dynamic objects of unknown dimensions, you could use a recursive function that uses Object.getOwnPropertyNames and the prototypes (someObject.__proto__) of those properties to handle the generation of fresh Objects for the properties of the destination object.
Hope that answers your question!
Edit: Added console output for the above script.
That does indeed look like a good solution if you know the object props.
But
JSON.parse( JSON.stringify( obj ) );
, though hacky, is much quicker to write!Oh okay. I misunderstood, I thought you were avoiding using that
JSON.parse( JSON.stringify( obj ) );
for some reason. Whoops!Have a good Turkey day, or a good Thursday.