Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Variable is treated as a string in JavaScript

Variable is treated as a string in JavaScript

Problem

I'm trying out the node-mysql module on node js. What I want to do is to be able to come up with an object like this:

{'room1':'Room 1','room2':'Room 2','room3':'Room 3'}

Here's the code:

var boom  = results;
   var rooms = [];
   var index = 0;
   var name = 'session';
    for(var b in boom){
        var ses = name + index;
        rooms[b] = {ses : boom[b]['ses_title']};
        index++;
    }

The ses Variable is being treated as a string in the code above. And I end up with something like this:

[{ses : 'class session'} , {ses : 'team session'}]
Problem courtesy of: Wern Ancheta

Solution

You can't assign key names like that. Use bracket notation and it should work:

var boom  = results;
var rooms = [];
var index = 0;
var name = 'session';
for(var b in boom){
 rooms[b] = {};
 rooms[b][name + index] = boom[b]['ses_title']};
 index += 1;
}
Solution courtesy of: KooiInc

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Variable is treated as a string in JavaScript

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×