0

I have looked all over google and i have found nothing that fits my needs. How would you add an item to an object. I basically have a string variable that i want as the key. Therefore i cant use obj.key = 'something';. I sort of want it like:

obj = {'somekey': 'somevalue'};

obj.add('someotherkey': 'someothervalue');
console.log(obj);

by obj.add() i mean someone's solution and then console says {'somekey': 'somevalue', 'someotherkey': 'someothervalue'} Does anyone know a way to do this. I don't care at what position it is just whether it is there. By the way i'm using node if that helps. If you have any questions on my code please ask.

SpirantSum2
  • 1
  • 1
  • 4
  • have you tried `obj.someotherkey = someothervalue` ? – Sonu Bamniya May 26 '20 at 12:39
  • I would consider this as duplicate. Here is exactly what you are looking for: https://stackoverflow.com/questions/1184123/is-it-possible-to-add-dynamically-named-properties-to-javascript-object – perellorodrigo May 26 '20 at 12:39
  • 3
    Does this answer your question? [Is it possible to add dynamically named properties to JavaScript object?](https://stackoverflow.com/questions/1184123/is-it-possible-to-add-dynamically-named-properties-to-javascript-object) – Hafnernuss May 26 '20 at 14:05

1 Answers1

-1

Very simple:

obj["somekey"] = "somevalue";

You can also use a variable instead:

let myVariable = "somekey";    
obj[myVariable] = "somevalue";

Or you just use normal object notation:

obj.somekey = "somevalue"
gian.gyger
  • 171
  • 4