how can i insert a variable string in a object notation (JSON)?

263 views Asked by At

Take this JSON Object as an example:

"pages": {
    "start": {
        ....
    },
    "page1": {
        ....
    },
    "page2": {
        ....
    },
    ....
}

Now via the jQuery ajax function I load the above JSON object and save it's result into a variable. So far so good. Then I have some html like this:

<div class="container" page-data="start">
    <h2></h2>
</div>    
<div class="container" page-data="start">
    <h2></h2>
</div>    
<div class="container" page-data="page1">
    <h2></h2>
</div>    
<div class="container" page-data="page2">
    <h2></h2>
</div>

Now I wrote this function to use the JSON data:

function createContent(el) {
    var page, $obj;
    page = [];
    $obj = el;
    $obj.each(function(index) {
        page[index] = $(this).attr('page-data');
        $(this).find('h2').html(jsonData.pages. + page[index] + .value);
    });
}
//here I start the function
$(document).ready(function(){
    createContent($('.container'));
});

What is not working is this part of the above function:

$(this).find('h2').html(jsonData.pages. + page[index] + .value);

This is pretty obvious, as the object notaion isn't just a string value. Now, is there any way how I can combine this to a valid object notation?

1

There are 1 answers

0
techfoobar On BEST ANSWER

Use the [] notation to access the object members.

...
$(this).find('h2').html(jsonData.pages[page[index]].value);
...