0
$obj = new Object();
$obj.surname = "smith";

$field_name = "surname";

alert($obj.$field_name); //error!!

Wth? How do I do this with js? I need to access all values in an object within a foreach but I can't manage to access obj proprerties by reference!

2 Answers 2

4

$obj[$field_name] will do. It's the same with the literal keys: you may use object['id'] as well as object.id - the latter is shorter, though. )

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

Comments

1

you can access each property by entering the name of the property as a key .

JavaScript automatically creates a associative array for each object where the keys are properties names and values are there value .

So instead of $obj.$field_name use $obj[$field_name] because $obj.feild_name is like $obj."surname"

check this Objects as associative arrays

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.