Can you dynamically add properties to a JavaScript/JSON object using values from a string?
let myObj= {};
for{prop in propsToAdd){
myObj.addProperty(prop.name, prop.type);
}
myObj.addProperty = function (name, type) {
// need to create another JSON object
// with the property name as the name of the property
// and a property called type with the value of the parameter type
}
For example:
myObj = {}
myObj.addProperty("title","string");
myObj.addProperty("id","integer")
This should result in:
myObj = {
"title": {
"type": "string"
},
"id": {
"type": "integer"
},
}
I am considering using JSON.stringify
and JSON.parse
, but I'm open to a more elegant solution.