RedJax
RedJax

Reputation: 123

Getting undefined from javascript array of arrays

This is linked to my previous question however its slightly different and is a whole new question... I have an array, which after some nice PHP looks like this:

var series = {
    "001":{
        "game":"Portal 2",
        "name":"Portal 2"
    },
    "002":{
        "game":"Minecraft",
        "name":"241"
    },
    "003":{
        "game":"Minecraft",
        "name":"HackMine"
    },
    "004":{
        "game":"Mass Effect 3",
        "name":"Mass Effect 3"
    },
    "005":{
        "game":"League of Legends",
        "name":"League of Legends"
    },
    "006":{
        "game":"Half Life 2",
        "name":"The Hidden: Source"
    },
    "007":{
        "game":"Skyrim",
        "name":"Modded Skyrim"
    }
}

This bit is populated fine... Now my question is when this function is called, it always gives game and name the value undefined

function seriesIdOnBlur()
{       

    var id = parseInt(document.getElementById("series_id").value);

    if (series[id] == null)
    {
        var message = "The Series ID you input was invalid";
    }
    else
    {
        var seriesId = series[id];

        var game = seriesId['game'];
        var name = seriesId['name'];
        var message = "You've inputted the id for the game: " + game + " for the series: " + name;
    }

    document.getElementById("series_id_check").innerHTML = message;
}

Upvotes: 0

Views: 105

Answers (2)

c-smile
c-smile

Reputation: 27460

This:

series = {
    "001":{
        "game":"Portal 2",
        "name":"Portal 2"
    },
    "002":{
        "game":"Minecraft",
        "name":"241"
    } ... };

is an object literal so you have Object of Objects rather than Array of Arrays as you stated.

You will need array of objects in order your code to work:

series = [
    {
        "game":"Portal 2",
        "name":"Portal 2"
    },
    {
        "game":"Minecraft",
        "name":"241"
    } ... ];

Upvotes: 1

Eric
Eric

Reputation: 97565

You're shooting yourself in the foot with those leading 0s: series['001'] is not the same as series['1']. Either cut the parseInt call (forcing the user to type '001'), drop the leading 0s:

var series = {
    "1":{
        "game":"Portal 2",
        "name":"Portal 2"
    },
    ...
    "7":{
        "game":"Skyrim",
        "name":"Modded Skyrim"
    }
}

or use an array:

var series = [
    {
        "game":"Portal 2",
        "name":"Portal 2"
    },
    ...
    {
        "game":"Skyrim",
        "name":"Modded Skyrim"
    }
]

Upvotes: 6

Related Questions