-1

I am trying to use a variable when declaring an object:

var name1 = "object1";
var data1 = 3;
create_object(name1, data1);

function create_object(name, data) {
  var x = {
    name: data
  }
  return x
}

I want x to be stored as

var x = {
  object1: 3
}

But my function will make

var x = {
  name: 3
}

Is there a way to pass a variable when declaring the name of a child inside an object?

Thanks a lot

N8888
  • 670
  • 2
  • 14
  • 20
Y. Chen
  • 183
  • 1
  • 10

1 Answers1

1

To specify a name of a property from a variable you need to use the square brackets notation like this:

function create_object(name, data) {
  var x = {};
  x[name] = data;
  return x;
}
bhspencer
  • 13,086
  • 5
  • 35
  • 44