是否可以通过使用字符串中的值向 javascript / json 对象添加属性?
let myObj= {};
for{prop in propsToAdd){
myObj.addProp(prop.name, prop.type);
}
myObj.addProp = function (name, type) {
// here i need to add another json object
// with the name as the name of the property
// and a property called type with the value of the param type
}
例子:
myObj = {}
myObj.addProb("title","string");
myObj.addProp("id","integer")
结果应该与以下相同:
myObj = {
"title": {
"type": "string"
},
"id": {
"type": "integer"
},
}
我正在考虑使用JSON.stringify
(一起构建字符串)和JSON.parse
.
但如果有更优雅的方式就好了。