0

I am new to javascript.
I want to have an object with this structure.

Users = {
    User1 : {
        "name" : "name",
        "id"   : "123"
    }
    User2 : {
        "name" : "name",
        "id"   : "123"
    }
}

so I should define Users like this:

 var Users = {};

How can I add new User to Users? and How can I read and write from users inside Users object like this:

 // reading
 User1_name = Users.User1.name;

 // writing
 Users.User1.name = "new name";
3
  • 3
    What's the question? You code seems OK so far. Commented Nov 1, 2013 at 10:11
  • it's not a code, I want the code Commented Nov 1, 2013 at 10:12
  • It is pretty much valid code. Just, as mentioned, a comma is missing. Commented Nov 1, 2013 at 10:15

2 Answers 2

3

Your code is fine (except the missing comma @Philipp pointed), but you can use an array too:

var users = [
    {
        "name" : "name",
        "id"   : "123"
    },
    {
        "name" : "name",
        "id"   : "123"
    }
];

var userName = users[0].name;

users[0].name = "new name";
Sign up to request clarification or add additional context in comments.

1 Comment

+1 This is a better way to handle users in an easy enumerable way.
2

You can define users like this, you are just missing a comma

Users = {
    User1 : {
        "name" : "name",
        "id"   : "123"
    } <--
    User2 : {
        "name" : "name",
        "id"   : "123"
    }
}

Should be ( with var added for clarity )

var Users = {
    User1 : {
        "name" : "name",
        "id"   : "123"
    },
    User2 : {
        "name" : "name",
        "id"   : "123"
    }
}

Reading and writing can be done the way you described.

To add a new user, you could do something like this

Users["User3"] = {
    "name" : "name3",
    "id"   : "1234"
}

2 Comments

User3 comes from php, so it can be anything. is it valid to be var username = 'somename' And Users.username = { 'name' : 'name', 'id' : '123' } ?
Users[username] = { 'name' : 'name', 'id' : '123' }

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.