0

I am getting the name of the user everytime the script is called and storing it in a variable called name

And I have a object which is initially null and I want it to be populated based on the name that I read.

I have this object

var usernames = {
    name1: {
        name: "ajey",
        room: 1,
        isStudent: true,
        isTeacher: false
    },
    name2: {
        name: "ajey-teacher",
        room: 1,
        isStudent: false,
        isTeacher: true
    },
    name3: {
        name: "batman",
        room: 2,
        isStudent: true,
        isTeacher: false
    }
};

Later I would print all the objects along with its key and value in the usernames object like,

for(var i in usernames) {
 console.log(i.name1.name);
}

Here is the fiddle I am working on but I am having some issues. Demo

2 Answers 2

2

Use

for (var i in usernames) {
    console.log(usernames[i].name);
}

DEMO

Sign up to request clarification or add additional context in comments.

1 Comment

Got it. And how do I create the name1, name2, name3 objects and so on dynamically ? based on the variable name
2

The loop should be:

for (var i in usernames) {
    console.log(usernames[i].name);
}

When you use for-in, the variable is set to the property name. To use a dynamic property name, you have to use bracket syntax; dot syntax is only for literal properties.

You can also use bracket syntax to create properties dynamically:

usernames['name'+i] = {
    name: "batman",
    room: 2,
    isStudent: true,
    isTeacher: false
};

5 Comments

Got it. And how do I create the name1, name2, name3 objects and so on dynamically ? based on the variable name
Added explanation of that.
Although I wonder why you're using an object. Usually when you find yourself using names with consecutive numbers like this, you should actually be using an array.
Actually I am building a chat application in node and socket. So initially when the client connects to the chat, I am storing all the details like name, room no, role inside an object(which is his username) and this object is stored inside a global usernames object. So with this later I can process in which room or role the user belongs to. Is this a good approach ?
OK, that makes sense. These names were just examples, in real life they wouldn't have a pattern like this.

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.