abolotnov
abolotnov

Reputation: 4322

Select JavaScript array element item with jQuery selectors

I have some json and jQuery doesn't seem to select its elements correctly. The json document I am referencing is available here: http://pastebin.com/bM3BvD2F.

the json is a array of elements and I'm trying to select one with required ID.

(you can copy-paste to http://jsonviewer.stack.hu/ for a nice folded view of it)

Here's the code I have problems with:

    //get current picture ID - will return '2' - correct value    
    var currentID = window.location.hash ? window.location.hash.substring(1) : allImages[0]["id"];

    //this line will alert name attribute value for a picture with (id = 4) - wrong :(
   alert($(allImages[id=currentID])[0].name);

Upvotes: 2

Views: 2936

Answers (2)

Shadow Wizard
Shadow Wizard

Reputation: 66389

allImages is a plain array, so allImages[id=currentID] will cause temp variable called id to be created, assigned the value of currentID and return 2, causing the third element in the array to be returned. This element has indeed id of 4.

What you need is "deep search" and one way to do this is using the .map function:

var name = jQuery.map(allImages, function (value) {
    return (value.id == currentID) ? value : null;
})[0].name;

Quick test case: http://jsfiddle.net/PWPcE/

Upvotes: 3

Billy Moon
Billy Moon

Reputation: 58521

Try:

alert($(allImages[id=currentID]).attr('name'));

I think by selecting the 0th element, you are selecting the 1st character from the answer you want.

Upvotes: 0

Related Questions