0

Why i am unable to pass "abc" to someKey

function convertToKeyValuePair(someKey,someValue){

    var map = {someKey : someValue};
    return JSON.stringify(map);
}
print(convertToKeyValuePair("abc","xyz"));

O/P = {"someKey":"sdfdf"}

Expected O/P = {"abc":"xyz"}

Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • You want dynamic keys, e.g. `var map = {[someKey]: someVaue};` – junvar Jan 28 '20 at 19:29
  • 1
    I believe that output is O/P = `{"someKey":"xyz"}`. If so just use computed property values - `var map = {[someKey]: someValue};` – Ori Drori Jan 28 '20 at 19:30
  • See also here: https://stackoverflow.com/questions/11508463/javascript-set-object-key-by-variable –  Jan 28 '20 at 19:32

3 Answers3

0

As you’re passing key dynamically so you’ve to use bracket around it like: { [someKey]: someValue }

Muhammad Ali
  • 2,538
  • 2
  • 16
  • 21
0

You want dynamic keys.

let key = 'yo';
let obj = {key: 0}; // creates {"key": 0}
let objDynamic = {[key]: 0}; // creates {"yo": 0};

console.log(obj);
console.log(objDynamic);
junvar
  • 11,151
  • 2
  • 30
  • 46
0

As answered by the comment of @junvar, passing keys to objects without quotes is syntactic sugar and both of the following examples will give the same result:

{ "someVar": someValue }
{ someVar: someValue }

To use the value of a variable as a key you have to use square brackets as in:

{ [someVar]: someValue }