Brieuc
Brieuc

Reputation: 4114

Javascript access nested object from dynamic name

I have this object :

var steps = {

    'step0' : {
        tour_title:"Lorem ipsum dolor",
        tour_content:"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin tristique aliquam justo, quis eleifend metus porta congue. Nam facilisis elit gravida lorem placerat, at ultricies lorem porta. Aenean faucibus libero gravida adipiscing aliquam. Nulla porttitor metus justo, in lacinia purus consectetur consectetur.", 
        position:"midle"
    }, 
    'step1' : {
        tour_title:"Lorem ipsum dolor 2",
        tour_content:"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin tristique aliquam justo, quis eleifend metus porta congue. Nam facilisis elit gravida lorem placerat, at ultricies lorem porta. Aenean faucibus libero gravida adipiscing aliquam. Nulla porttitor metus justo, in lacinia purus consectetur consectetur.", 
        position:"midle"
    }   
}

I also have a variable that is defining which step i am (it is declared outside my js file) :

var user_step = <?php echo $this->tourfinder($user_id); ?> // let's use var user_step = 0 for the example

What i'm gonna write is totally wrong but this is the logic i'd like to use :

var actual_tour_title = steps.step+user_step+.tour_title; // so it should give step.step0.tour_title 

What would be the correct way to access it that way? I've read several posts about arrays and objects in javascript on stackoverflow and else but i can't figure it out why it can't be as simple as php.

Upvotes: 0

Views: 92

Answers (4)

rukimira
rukimira

Reputation: 66

I did not fully understand but my guess is if you want to handle this JSON object in Javascript, you can use both ways:

steps.step0.tour_title

steps["step0"].tour_title

With some variable, you can do:

steps["step" + user_step].tour_title

Upvotes: 1

joncys
joncys

Reputation: 1350

You're not very far from the truth in your pseudo-code. The correct way to dynamically access a key in the JavaScript object is as follows:

var current_step = 1;
var actual_tour_title = steps['step' + current_step].tour_title;

You can access keys either by using dot syntax or by referencing the keys as strings:

var obj = { data: 'I like turtles!' };
// two ways to get this
var result = obj.data; /* or */ var result = obj["data"];

Upvotes: 1

Cheruvian
Cheruvian

Reputation: 5867

Objects in javascript are simply stored as associative arrays so retrieving properties is as simple as using your property name as a key.

steps["step" + user_step].tour_title;

Upvotes: 1

hindmost
hindmost

Reputation: 7195

Quote:

...any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number) can only be accessed using the square bracket notation.

So the code should look like this:

var actual_tour_title = steps[step+user_step].tour_title;

Upvotes: 1

Related Questions