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,910
  • 1
  • 14
  • 31
Mary
  • 1,005
  • 2
  • 18
  • 37

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
  • 376,160
  • 25
  • 347
  • 392
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,910
  • 1
  • 14
  • 31