0

My code is as follows:

var currency = "USD";
var value = 100;

function test(currency, value) {
    var myObject = {("" + currency): value};
    console.log(myObject);
}

test(currency, value);

I'm trying to get an object as follows:

{"USD": 100}

How do I fix my code to do this?

Sanchit Patiyal
  • 4,786
  • 1
  • 13
  • 31
Mary
  • 825
  • 1
  • 13
  • 29

2 Answers2

1

You could take a computed property name for the object.

function test(currency, value) {
    return { [currency]: value };
}

var currency = "USD",
    value = 100;

console.log(test(currency, value));
Nina Scholz
  • 351,820
  • 24
  • 303
  • 358
1

In javascript we can add object with:

  • dot notation
  • square brackets

But only second case allows to access/add properties dynamically like this-

var currency = "USD";
var value = 100;
var myObject = {};

function test(currency, value) {
  myObject[currency] = value;
  console.log(myObject);
}

test(currency, value);
Sanchit Patiyal
  • 4,786
  • 1
  • 13
  • 31