0

Is it possible to add a property to a javascript / json object by using a value from a string?

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
}

example:

myObj = {}
myObj.addProb("title","string");
myObj.addProp("id","integer")

should result as same as:

myObj = {
  "title": {
    "type": "string"
  },
  "id": {
    "type": "integer"
  },
}

I was thinking of the use of JSON.stringify (building strings together) and JSON.parse.

But it would be good if there's a more elegant way.

Gobliins
  • 3,848
  • 16
  • 67
  • 122

5 Answers5

2

You could do something like this. Note you probably want addProp on both, and not 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);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
2

You can use a constructor instead of alter Object prototype :

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

var myVal = new myObj();
1

You can simply use the brackets notation to add properties to your objects :

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);
Zenoo
  • 12,670
  • 4
  • 45
  • 69
1
myObj.addProp = function (name, type) {
   this[name] = {type: type};
}

You can add a property to an object in two different ways.

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

On the above function, this refers to the object you want to add properties to.

Charlie
  • 22,886
  • 11
  • 59
  • 90
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);
Nishant Dixit
  • 5,388
  • 5
  • 17
  • 29