-1
function one(data) {
  someotherfunction({
    data.id: {
      name: data.nm,
      age: data.age
    });
}
one({ id: 2, name: "Stack", age: "20" });

Why can't I set data.id as the property name of that sub-object? I tried many ways of setting the id but it only works if I set it to some string name....

var i = data.id;
someotherfunction({i:{name:data.nm,age:data.age});

It doesn't recognize the variable either?

ykadaru
  • 1,018
  • 1
  • 13
  • 27
  • Note that ECMAScript 2015 has [*computed property names*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer), however support may not be sufficient for them to be used in general on the web. – RobG Nov 10 '15 at 03:44

3 Answers3

1

I don't think that's a valid propertyName or identifier and it's certainly not a string literal. Try it like this:

function one(data){
   var nObj = { };
   nObj[data.id] = { name : data.nm, age: data.age };
   someotherfunction(nObj);
}

one({id:2,name:"Stack",age:"20"});
//nObj = { 2 : { name : "Stack, age : "20" } }
MinusFour
  • 13,090
  • 3
  • 27
  • 36
1

From RobG's answer at: https://stackoverflow.com/a/6500668

In an object literal (ECMA-262 §11.1.5 calls it an "object initialiser") the key must be one of:

  1. IdentifierName
  2. StringLiteral
  3. NumericLiteral

You could do something like:

function one(data) {
   var d = {};
   d[data.id] = { name: data.name, age: data.age };
   someotherfunction(d);
   }
one({ id: 2, name: 'Stack', age: '20' });

Fiddle with the code at:
http://jsfiddle.net/sna04g8m/1

Community
  • 1
  • 1
Dem Pilafian
  • 5,184
  • 6
  • 36
  • 63
0

You may be looking for computed property names, a new feature in ECMAScript 2015 that is supported in some browsers, e.g.:

// Requires support for ECMAScript 2015 computed property names
function one(data) {
  return {
    [data.id]: {
      name: data.name,
      age: data.age
  }};
}

document.write(JSON.stringify(one({ id: 2, name: "Stack", age: "20" })));
RobG
  • 134,457
  • 30
  • 163
  • 204