user3675085
user3675085

Reputation: 51

Javascript and Jquery: Uncaught TypeError: Cannot read property 'length' of undefined

Currently I'm writing a site where one feature is to allow the user to type in the name of a card (the game's Hearthstone), and add it to a deck on the site. I'm using JSON data from http://hearthstonejson.com/json/AllSets.json , but I'm having trouble querying that data.

Right now I have:

// On user submission, searches for the inputted card name and places it into
// the deck if a match is found
$("#cardSearch").submit(function(){   
    card = $("#userInput").val();
    console.log("Card searched: " + card);
    $.getJSON("http://hearthstonejson.com/json/AllSets.json",function(cards){
       // cards = JSON.parse(cards);
        console.log(cards);
        $.each(cards.name, function(key, val){ 
            if (val.name == card) {
                console.log("Success, I found :" + val.name);
                return;
            }
        });   
    }   
    );
});

My error is Uncaught TypeError: Cannot read property 'length' of undefined , referencing line 631 from the latest version of jquery.

I thought that maybe I had to parse the data, as you can see with the commented line of code in the middle. But, when I add that line, I get a different error:

Uncaught SyntaxError: Unexpected token o.

I'm not sure where to proceed.

Thanks for the help - I'm pretty new to this!

Upvotes: 1

Views: 2255

Answers (2)

super
super

Reputation: 2328

Try this:

var card = $("#userInput").val();
$.getJSON("http://hearthstonejson.com/json/AllSets.json", function (cards) {
    //Returns a JSON object where cards are grouped into something like this Basic, Credits, Debug etc
    //Each of these groups contains an array of cards
    //So the first step is to loop through the groups and inside this loop through the array of cards.
    $.each(cards, function (key, val) {
        //Here val is an array of cards
        //In order to get each card we have loop through val.
        $.each(val, function (index, data) {
            //Here data is refferd to as individual card
            if (data.name == card) {
                console.log("Success, I found :" + data.name);
                return;
            }
        });
    });
});

JSON cards:

Object {Basic: Array[212], Credits: Array[17], Debug: Array[39], Expert: Array[392], Missions: Array[37]…}

We have to use cards.Basic[index] to get a particular card

Object {id: "GAME_004", name: "AFK", type: "Enchantment", text: "Your turns are shorter."}

Here is the demo

Upvotes: 1

KennyC
KennyC

Reputation: 961

The error means $.each could not access the object as an array which means it does not have the length property.

Your code should be:

$.each(cards, function(key, val)

Upvotes: 0

Related Questions