2

I want to create a json object in node.js that looks like this;

{ WantThisName: { property_length: 8 } }

Here is my code;

var property_name = "WantThisName"
var length = 8;

var Obj_bin;
Obj_bin= {property_name: {property_length:length} };
console.log (Obj_bin);

The console output is;

{ property_name: { property_length: 8 } }

The problem lies with property_name not getting the contents of the variable property_name.

  • Being discussed on meta [Is a question a duplicate when it has the same answers?](http://meta.stackoverflow.com/q/318996) (cc @thefourtheye) – Bhargav Rao Mar 15 '16 at 07:38

2 Answers2

0

try

Obj_bin = {};
Obj_bin[property_name] = { property_length: 8 };
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
  • Sorry, it does not work. I get error message `Obj_bin[property_name] = { property_length: 8 }; ^ TypeError: Cannot set property 'WantThisName' of undefined` –  Mar 15 '16 at 06:10
  • It works now! Sorry, my points are too low to give you an upvote. –  Mar 15 '16 at 06:12
  • @LitAiy no worries, glad to help – gurvinder372 Mar 15 '16 at 06:14
0

You can use computed (dynamic) property names:

> foo = "foozz"
'foozz'
> {[foo]: 42}
{ foozz: 42 }

They're part of the Enhanced Object Literals of es2015 (https://github.com/lukehoban/es6features#enhanced-object-literals).

For your example:

> var property_name = "WantThisName";
var property_name = "WantThisName";
undefined
> var length = 8;
undefined
> {[property_name]: { property_length: length}}
{ WantThisName: { property_length: 8 } }
>
thebjorn
  • 26,297
  • 11
  • 96
  • 138