0

I have similar to next json:

{
    'igor': {'password': '12345678', 'color': 'white'),
    'ruslan': {'password': '87654321', 'color': 'black')
}

And also have variable

var name = 'igor';

How can I get password value, using this variable to detect name? I tried next:

obj[name['password']]

But it returns undefined; also tried:

obj.name['password']

As well it returns undefined. How should I get that value? Thanks.

1
  • obj[name]['password'] Commented Jul 16, 2015 at 12:28

2 Answers 2

1

As Nano commented, to access "password" for the object with the key "igor" you need to use obj[name]['password']. This is because you have two objects one with "igor" as the key, and one as "ruslan" as the key. You could also use

var igor = obj['igor'];
var igorsPassword = igor['password'];

In addition unixarmy's form is not wrong, and the following is correct.

var igor = obj.igor;
var igorsPassword = igor.password;

That being said however, if the property name has spaces in it it must be accessed using the obj['property name'] form, it cannot be done with obj.property name since the space between property and name serves as a syntax separator when not in a string/regular expression.

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

2 Comments

i cannot know before is it igor or nor, i have server-side and client-side, when user enters his name and password, it goes to server-side, and from there i take variable with name, so I can't do: var igor = obj.igor
@IgorBarakaiev Ok, I was not aware of the circumstances. That being said, the obj[property] form is still very much valid.
0

Your JSON example is not valid!

Anyway, you can use the following syntax: obj[name].property.

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.