Check out this alternative method using a reviver function. The great thing about this approach is that the parsing process handles object instantiation directly, eliminating the need for multiple steps.
let shapeTypes = { 'Rectangle': Rectangle }, //similar to THREE in your original code
jsonShape = '{ "shape": ["Rectangle", [2, 4]] }',
createdShape = createShapeFromJson(jsonShape);
console.log(createdShape);
function instantiateObject(constructor, arguments) {
let instance = Object.create(constructor.prototype);
constructor.apply(instance, arguments);
return instance;
}
function createShape(type, parameters) {
return instantiateObject(shapeTypes[type], parameters);
}
function createShapeFromJson(jsonString) {
return JSON.parse(jsonString, function (key, value) {
return key ? value : createShape(value.shape[0], value.shape[1]);
});
}
function Rectangle(height, width) {
this.height = height;
this.width = width;
}