By thinkanotherone


2012-03-14 18:45:56 8 Comments

var test = "test123"
var test123 ={
    "key" + test: 123
}

This code doesn't work. What is wrong with "key" + test ?

6 comments

@max 2012-03-14 18:50:36

You can but not with literal notation (pre ES6).

var test123 = {};
test123["foo" + "bar"] = 'baz';

test123.foobar === 'baz'; // true

@Daniel Tonon 2015-02-26 03:28:44

Thanks for the simple answer, that's just what I was looking for :)

@Ben 2016-03-08 20:05:59

With ES6, you can define dynamic keys within an object literal:

const test = "test123"
const test123 = { ["key" + test]: 123 };

@Bhushana Rao Kadimi 2016-02-04 12:03:18

--HTML--
<div id="name1"></div>
<div id="name2"></div>
<div id="name3"></div>

--JS--
  function getJsonData(){
   var hr = new XMLHttpRequest();
   hr.open("GET", "bookJson.json", true);
   hr.setRequestHeader("Content-type", "application/json", true);
   hr.onreadystatechange = function() {
  if(hr.readyState == 4 && hr.status == 200) {

     var data = JSON.parse(hr.responseText);
   for(var i=0;i<3;i++){
     var a = "p"+(i+1)+"H";
     $("#name"+(i+1)).html(data[objName][a]);
     }


   }

 }
  hr.send(null);
}

---JSON--- save JSON file name as bookJson.json
 { "objName":
   {
    "p1H":"content1",
    "p2H":"content2",
    "p3H":"content3",
   }
  }
----------------------------------- 
 json object key name p1H,p2H,p3H ... 
 We want to dynamically get this keys in javacript instead of   **data[objName].p1H**. you can get dynamical key like **data[objName]["p1H"]**

@Tristan 2016-02-05 02:18:58

Please provide an explanation of your answer to help other users of the site. Code-only answers are not very useful and tend to be marked as low quality and potentially deleted.

@Bhushana Rao Kadimi 2016-02-10 04:44:01

Thanks for suggestion, i provided an explanation of my answer...

@jilykate 2016-02-04 12:13:37

Javascript provides two ways to define a property of an object:

  1. object.propertyName = value;

In this situation, the propertyName is un-editable, and un-computable. you cannot do the following:

    object.('property'+'Name')

as you can see

    object = {propertyName:value};
    object = {'propertyName':value};

they are equal

  1. you can use a variable as the property name with "[]";

you can do :

 var a  = "propertyName";
 object[a] = value;

and this time you have to use a string

object[propertyName] = value;//error
object["propertyName"] = value;//correct
object = {'propertyName':value};//correct
object = {propertyName:value};//correct

@pimvdb 2012-03-14 18:48:43

Because "key" + test is an expression and not an identifier nor a string literal nor a number literal, which are the only things that are allowed as the key in an object literal.

You have to use the [] notation after creating the object for such a dynamic key:

var test123 = {};
test123["key" + test] = 123;

An identifier is basically the same subset of characters that you can call a variable (letters, numbers, _ and $; may not start with a number), and a string literal is any string enclosed with ' or ".

So, the only types of keys you can use in an object literal are:

{
  a0:   true, // valid identifier
  $$_:  true, // same
  123:  true, // valid numeric literal
  012:  true, // same (octal)
  0xf:  true, // same (hex)
  "@":  true, // not allowed as an identifier
  '0a': true  // same
}

Reference: http://es5.github.com/#x11.1.5.

PropertyName :

IdentifierName

StringLiteral

NumericLiteral

@Felix Kling 2012-03-14 19:02:01

In addition, numbers are allowed in the object literal as well, such as 0 or 5e10 (but not -10 because - is not part of the number literal but the unary - operator).

@pimvdb 2012-03-14 19:04:55

@Felix Kling: Indeed they are, thanks.

@Krizz 2012-03-14 19:03:32

Your code is equivalent to test123.("key" + test) = 123 which may better help you to understand why it is wrong.

You need ["name"] notation to be able to access fields by their name in string. Other notations (yours and . one) require identifiers.

Related Questions

Sponsored Content

37 Answered Questions

[SOLVED] How do I remove a property from a JavaScript object?

34 Answered Questions

[SOLVED] var functionName = function() {} vs function functionName() {}

69 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 5294513 View
  • 6590 Score
  • 69 Answer
  • Tags:   javascript arrays

25 Answered Questions

44 Answered Questions

[SOLVED] How to replace all occurrences of a string in JavaScript

64 Answered Questions

[SOLVED] What is the most efficient way to deep clone an object in JavaScript?

86 Answered Questions

[SOLVED] How do JavaScript closures work?

19 Answered Questions

[SOLVED] Checking if a key exists in a JavaScript object?

48 Answered Questions

Sponsored Content