Phantom Phantom - 2 months ago 11
HTML Question

Displaying selected child node from url

I have a JSON type data source that has the following structure:

{
"list":
[
{
"id": "4167845External",
"personId": 4167845,
"profileId": 4268472,
"personType": "External",
"cat": "person",
"imageId": "10300600",
"extn": "88976",
"profileUrl":
[
"id-mark",
"mar123"
]}],


For the array
profileUrl
, I wrote the following JavaScript code to get it display on the web page:

function Staff(person) {
var list = "";
for (var i = 0; i < person.length; ++i) {
var record = person[i];
list +=
"<tr><td>"
+ record.profileUrl
+ "</td><tr>\n";
}
document.getElementById("showList").innerHTML = list;
}


and the page will display
id-mark,mar123
as I run it, but what should I do if I want to display
mar123
only ?

Answer

profileUrl is an array so you must access the property as if it was an array, e.g., record.profileUrl[1]:

function Staff(person) {
    var list = "";
    for (var i = 0; i < person.length; ++i) {
        var record = person[i];
        list += 
            "<tr><td>" 
            + record.profileUrl[1] 
            + "</td><tr>\n";
    }
    document.getElementById("showList").innerHTML = list;
}

An array in JavaScript is defined like this:

var myVar = [ "id-mark", "id-mark" ];

Each element can be accessed like this:

console.log( myVar[0] ); // outputs: id-mark
console.log( myVar[1] ); // outputs: mar123

or, can be looped through like this:

for (var i=0; i<myVar.length; i++) {
    console.log(myVar[i]);
}