admin管理员组

文章数量:1403364

Can someone tell me how to update the following code to just get the first item that's returned in an object (data)? I know using each() for just one item isn't very efficient and would like to improve it.

$(data).each(function(num, entry){
    if ( num > 1 ) return false;
});

Here's an example of what data is:

[
    {
        "id": 1,
        "title": "My post",
        "permalink":"http:\/\/site\/page.html\/",
        "date":" 2011-05-10 
    }
]

Can someone tell me how to update the following code to just get the first item that's returned in an object (data)? I know using each() for just one item isn't very efficient and would like to improve it.

$(data).each(function(num, entry){
    if ( num > 1 ) return false;
});

Here's an example of what data is:

[
    {
        "id": 1,
        "title": "My post",
        "permalink":"http:\/\/site.\/page.html\/",
        "date":" 2011-05-10 
    }
]
Share Improve this question edited May 10, 2011 at 20:32 Cofey asked May 10, 2011 at 20:13 CofeyCofey 11.4k16 gold badges54 silver badges75 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9

Update 2:

As data is just an array (I assume the JSON is already parsed (if not you can use jQuery.parseJSON or JSON.parse)), you can get the first element with simple array access:

var first = data[0];

Read more about arrays.


Old answer:

Try

$(data).first()      // returns jQuery object
// or
$(data).eq(0)        // returns jQuery object
// or 
$(data).get(0)       // returns DOM object
// or
$(data)[0]           // returns DOM object

depending on the data you have and what you want to do.

Update:

If data is actually a JavaScript object, then there is no need to pass it to jQuery (jQuery is mostly for working with the DOM).

Just loop over it with

for(var prop in data) {

}

But you cannot get the "first" property because they are unordered.

If it is an array, just use data[0].

To help you more, you should post what data is.

You can do this:

$(data).get(0); //same as $(data)[0]

本文标签: jQueryJavaScript equivalent of each() for a single elementStack Overflow