How do I create an empty copy of an object?
javascript
Solution
You could use a function that creates a copy of the object structure and uses a default value for each data type:
function skeleton(source, isArray) {
var o = Array.isArray(source) ? [] : {};
for (var key in source) {
if (source.hasOwnProperty(key)) {
var t = typeof source[key];
o[key] = t == 'object' ? skeleton(source[key]) : { string: '', number: 0, boolean: false }[t];
}
}
return o;
}
Demo: http://jsfiddle.net/Guffa/ym6ZJ/
Problem
I am creating some objects from JSON and I would like to make an empty copy of an object. I would have all the same properties but empty values. What are some good ways of doing this? Right now I am doing it as follows but would like it to be dynamic from the objects I create from the JSON I receive. ``` var myObject = { "Address": { "Address1": "", "Address2": "", "Address3": "", "Address4": "", "City": "", "": "", "": "", "Country": "", "Id": -1, "LastModified": "", "PostBackAction": null }, "Id": -1, "Amenities": "", "Directions": "", "LastModified": "", "LocalAttractions": "", "LocalLodging": "", "LocalRestaraunts": "", "Name": "", "Pictures": "", "Prices": "", "Region": 0, "PostBackAction": null }; ``` A possible solution that doesn't work because it copies the values. ``` var myObject = JSON.parse(JSON.stringify(objectToBeCopied)); ```