Maca
Maca

Reputation: 1689

Accessing values in JavaScript object

Question revised for clarity: Im having issue parsing json file. I want to output the value of the basename labeled "image_01". So the it will only outputs http://blog.url/news/images/201516.jpg

<div id="placeholder"></div>
<script>
var data={
    "items": [
        {
            "title": "This is The Title",
            "customFields": [
                {
                    "basename": "image_01",
                    "value": "<form mt:asset-id=\"352706\" class=\"mt-enclosure mt-enclosure-image\" style=\"display: inline;\"><a href=\"http://blog.com/news/images/20150116.jpg\">20150116.jpg</a></form>"
                }
            ],
            "permalink": "http://blog.com/index.php"
        }
    ]
}

document.getElementById("placeholder").innerHTML=data.items[0].title + " " + data.items[0].permalink+"--"+ data.items[0].customFields.basename.image_01;
</script>

http://jsfiddle.net/v57s2csa/ fixed

I think particular problem lies in

data.items[0].customFields.basename.image_01;

Upvotes: 0

Views: 56

Answers (3)

Kiba
Kiba

Reputation: 10827

customFields is an array. You need to access the values inside it with an index.

document.getElementById("placeholder").innerHTML=data.items[0].title + " " + data.items[0].permalink+"--"+ data.items[0].customFields[0].basename;
// Change is here -------------------------------------------------------------------------------------------------------------------^^^

http://jsfiddle.net/v57s2csa/1/

Upvotes: 1

Vinoth K
Vinoth K

Reputation: 106

There is no object called image_01 inside data. Instead of

data.items[0].customFields.basename.image_01;

use

data.items[0].customFields[0].value

Also a img tag inside Form to display image after appending,

http://blog.url/news/images/201516.jpg\"><img src='http://blog.url/news/images/201516.jpg'/></a></form>

Upvotes: 0

Ifedi Okonkwo
Ifedi Okonkwo

Reputation: 3646

Replace the javascript with:

  document.getElementById("placeholder").innerHTML=data.items[0].title + " " 
+ data.items[0].permalink+"--"+ data.items[0].customFields[0].basename.image_01;

to reflect that customFields is array, not object.

Upvotes: 0

Related Questions