If you have used Google/Blogger/YouTube/etc API with JSON format, you may have seen the link array like
entry = { "link": [ { "rel": "replies", "type": "application/atom+xml", "href": "http://example.com/link1", "title": "Post Comments" }, { "rel": "replies", "type": "text/html", "href": "http://example.com/link2", "title": "Comments" }, { "rel": "edit", "type": "application/atom+xml", "href": "http://example.com/link3", }, { "rel": "self", "type": "application/atom+xml", "href": "http://example.com/link4", }, { "rel": "alternate", "type": "text/html", "href": "http://example.com/link5", "title": "Example Title" } ] }
Usually, you want the one which type is text/html and a link to normal webpage. I used to write a for loop, every time I need to get that one. I do mean every time, who knows how much time I wasted in writing the same loop code.
I finally came up a quick and better way using jQuery:
var link = $($.grep(entry.link, function(link, idx) {return link.rel == 'alternate'})).prop('href'); // breakdown var link = $( $.grep(entry.link, function(link, idx) { return link.rel == 'alternate' }) ).prop('href');
Even its reasonably little longer one-liner, its much more clear than a for loop, and could be same clear for who is not familiar with jQuery. The only drawback I could think of is: it could be slower than for loop, though I haven’t tested.
jQuery accepts objects not just DOM, you can have some methods though you don’t have selector-like to filter, but in this case, $.grep is good enough for processing. The result will be an array of objects and I use prop() to extract the href attribute after the results are turned into jQuery object.
Certainly, you can use just match_results[0].href, directly access object’s href attribute. But you can not guarantee that match_results is not an empty array. If it is, you will get a Type Error, because your code tries to get undefined.href.
Using prop(), it will fail silently by returning undefined and you can check it or just leave it in <a/> if you don’t care.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.