0

是否可以通过使用字符串中的值向 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.

但如果有更优雅的方式就好了。

4

5 回答 5

2

你可以做这样的事情。请注意,您可能都想要addProp,而不是addProb

const myObj = {};
// keep the function from being printed when printing the object
Object.defineProperty(myObj, 'addProp', {
  value: function addProp(key, type) {
    myObj[key] = { type };
  },
  enumerable: false
});
  
myObj.addProp("title","string");
myObj.addProp("id","integer");
console.log(myObj);

于 2018-05-28T09:58:21.010 回答
1

您可以简单地使用brackets符号为您的对象添加属性:

myObj[name] = {type: type};

let myObj = {};

myObj.addProp = (name, type) => {
  myObj[name] = {type: type};
}

myObj.addProp("title", "string");
myObj.addProp("id", "integer");

console.log(myObj);

于 2018-05-28T09:57:06.370 回答
1
myObj.addProp = function (name, type) {
   this[name] = {type: type};
}

您可以通过两种不同的方式向对象添加属性。

myObj.prop = 'val';
myObj['prop'] = 'val'

在上面的函数中,this指的是要添加属性的对象。

于 2018-05-28T09:58:18.217 回答
1

let myObj = {};

myObj.addProp = (name, type) =>  {
    myObj[name] = {type: type};
}

myObj.addProp("title","string");
myObj.addProp("id","integer");

delete myObj.addProp;

console.log(myObj);

于 2018-05-28T09:59:00.813 回答
1

您可以使用构造函数而不是更改对象原型:

function myObj() {
  this.addProp = function(name, type) {
    this[name] = {type: type};
  }
}

var myVal = new myObj();
于 2018-05-28T10:04:13.663 回答