Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript variable object keys [duplicate]

I am attempting to add a variable key, with no luck.

Here's what I got so far:

mysql('translations',{
    check: 'element_id',
    element_id: element_id,
    {'lang-'+lang_id}: value
});

The variable key is the last line of the function.

Any ideas?

like image 545
Ilya Karnaukhov Avatar asked Sep 29 '12 10:09

Ilya Karnaukhov


2 Answers

You can't use expressions for the identifiers in an object literal.

First create the object, then you can use dynamic names:

var obj = {
  check: 'element_id',
  element_id: element_id,
}

obj['lang-'+lang_id] = value;

mysql('translations', obj);
like image 100
Guffa Avatar answered Oct 14 '22 23:10

Guffa


You can do this:

var x = {
    check: 'element_id',
    element_id: element_id    
};
x['lang-'+lang_id] = value;

mysql('translations', x);
like image 34
techfoobar Avatar answered Oct 14 '22 22:10

techfoobar