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
.
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 } }
>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments