Heather
Heather

Reputation: 13

accessing JSON array item from another array

I'm a JS n00b, so my apologies for asking something so simple. (It's so simple that the rest of SO is providing more complex answers than I need.) I have a JSON array like this:

var comics = {"spider":"Spiderman", "bat":"Batman", "super":"Superman", "aqua":"Aquaman"};

And I want to access items in that array from another array, like so:

var childhood_heroes = {"fire":"Firefighters", "jordan":"Michael Jordan", "superhero":[comics.super, comics.bat]};

I'm attaching it with jQuery to a div in my HTML with:

$('#which_heroes').click(function() {
    $('#jobs').html(childhood_heroes.fire);
    $('#sports').html(childhood_heroes.jordan);
    $('#supers').html(childhood_heroes.superhero);
});

The first two work when the third is absent. The presence of the third breaks everything. What am I doing wrong?

Upvotes: 1

Views: 631

Answers (4)

Alex K.
Alex K.

Reputation: 175816

The pair: "super":"Superman" will cause probs as super is reserved, so comics.super will raise an error in IE at least.

Rename it, or use comics["super"] notation.

Upvotes: 0

Mike Samuel
Mike Samuel

Reputation: 120516

Make sure comics is initialized before childhood_heroes.

And not to nitpick, but neither of the things you defined are JavaScript or JSON arrays. They're only "arrays" in the very loose sense of "associative arrays".

Upvotes: 0

Björn
Björn

Reputation: 2648

You're accessing an Array where you probably want a String, you can use join() to put all the entries in the superhero array into a string:

$('#supers').html(childhood_heroes.superhero.join(", "));

Upvotes: 0

Robert
Robert

Reputation: 21388

This

$('body').html(["one","two"]);

Produces

Uncaught Error: NOT_FOUND_ERR: DOM Exception 8

So, your issue is that you're passing an array of strings to the jQuery .html() function, which apparently doesn't handle it too well. Turn it into a string before you pass it, something like

$('#supers').html(childhood_heroes.superhero.join(', '));

should work.

The two valid arguments for .html() from http://api.jquery.com/html/ are

html( htmlString  )
    .html( htmlString )
    .html( function(index, oldhtml) )

Upvotes: 3

Related Questions