1

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..

3 Answers 3

2

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;
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot, i wasted my time debugging these and searching for ans over internet, Finally your answer resolved the issue. Thank you..
Small question, is there something like size limit for javascript associative object storage?
:) If there is, i've not hit it yet, and I've made some pretty big objects at times. Don't worry, cross that bridge once you get there. This way you'll just waste time browsing for information you might never need. Just finish the project :)
2

You need square bracket syntax:

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

Basically genID must be used where expression is expected (inside square brackets). You are using it on the left side when object literal is expected. genID is treated there as a constant identifier and it is not evaluated.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.