Search code examples
javascriptobjectassociative

Error while creating javascript object property


I'm trying to create a javascript associative object, every thing works fine, but variable passed to create property name is not working, instead of storing variable value its converting variable into string and show variable name itself.

Quick Sample Below

var users = {};
var genID = someId;

createObj('userID', function(userID, username, email) {
users[userID] = { genID: { a: a, b: b, c: c, d: d } };
})

Expected result;

users = { 1: { 11: { a: 1, b: 2, c: 3, d: 4 } } }

Getting result;

users = { 1: { genID: { a: 1, b: 2, c: 3, d: 4 } } }​

Please help me to resolve these. Thank You..


Solution

  • If you look at what you did. The first thing worked: users[userID]. However, the second one genID didn't. That's because when you're using object notation, it assumes you're typing in the 'name' not a variable, so it doesn't resolve that. better would be:

    var obj = {};
    obj[genID] = {a: a, b: b, c: c, d: d};
    users[userID] = obj;