-1

I wish to use a variable as json key in javascript

var chtid = "1234" firebase.database().ref().set ({chtid :"hi"});

where chtid would be a variable

I tried this way but to no success

var chtid = "1234" firebase.database().ref().set ({[chtid] :"hi"});

Any simple soulution please.

sam
  • 688
  • 1
  • 12
  • 35
  • What does "no success" mean? Did you get the wrong result? Did you get an error message? – Quentin Sep 15 '17 at 08:14
  • do you want to use chtid as a value? then `{chtid:chtid}` will be right. But if this is what you want, I recommend you to change variable name. :) – Canet Robern Sep 15 '17 at 08:14
  • @CanetRobern — The question is quite clear that they want the key to be the value of the chtid variable. – Quentin Sep 15 '17 at 08:14
  • @Quentin I am getting `chtid` as a key in firebase instead of 1234 – sam Sep 15 '17 at 08:15
  • @sam — When you use `{[chtid] :"hi"}`? – Quentin Sep 15 '17 at 08:15
  • Its the same as `chtid` producing same results – sam Sep 15 '17 at 08:17
  • I can't reproduce that problem — http://jsbin.com/facajusawi/1/edit?js,console – Quentin Sep 15 '17 at 08:18
  • @Quentin oh.. sorry. forgive my misunderstanding.. – Canet Robern Sep 15 '17 at 08:18
  • sorry its giving syntax error `firebase.database().ref().set ({[chtid] :[{usr : $scope.usrid, msg : $scope.chatmsg.msg, time : dte }]});` ERROR is `I/chromium(10204): [INFO:CONSOLE(421)] "Uncaught SyntaxError: Unexpected token [", source: file:///android_asset/www/js/controllers.js (421) ` – sam Sep 15 '17 at 08:19
  • Whatever you are using to execute the JS doesn't support a new enough version of JS to support that feature. Either get a transpiler or use one of the alternative approaches on the duplicate question. – Quentin Sep 15 '17 at 08:20
  • Duplicate https://stackoverflow.com/questions/2274242/using-a-variable-for-a-key-in-a-javascript-object-literal – HD.. Sep 15 '17 at 08:30
  • bhosdi walo madar chod jab answer nahi kar pa rahe to maa ku chudwa rahe downvote kar k – sam Sep 15 '17 at 08:32

1 Answers1

0

Put it on a variable first:

var obj = {};
var chtid = "1234"
obj[chtid] = "Hi";
firebase.database().ref().set (obj);

hope that helps

masterpreenz
  • 2,280
  • 1
  • 13
  • 21