Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use variable as object index

I'm trying to find how to pass a variable as object index, for example:

function createObject(index,value){
  var data = {index:value};
  console.log(data);
}

createObject('hello','world');

//result Object { index="world"} instead of Object { "hello"="world"}

I couldn't find this specific answer so far..

Thanks!

like image 672
Crash Override Avatar asked May 23 '26 09:05

Crash Override


1 Answers

You can use object[index] notation:

function createObject(index,value){
    var data = {};
    data[index] = value;
    console.log(data);
}
like image 173
Denis Avatar answered May 25 '26 23:05

Denis