jQuery Grouping Similar Items w/ Object Literal
So I have this structure setup:
<ul>
<li>http://www.youtube.com/watch?v=dw1Vh9Yzryo</li> (Vid1)
<li>http://www.youtube.com/watch?v=bOF3o8B292U</li> (Vid2)
<li>http://www.youtube.com/watch?v=yAY4vNJd7A8</li> (Vid3)
<li>http://www.youtube.com/watch?v=yAY4vNJd7A8</li>
<li>http://www.youtube.com/watch?v=dw1Vh9Yzryo</li>
<li>http://www.youtube.com/watch?v=bOF3o8B292U</li>
<li>http://www.youtube.com/watch?v=yAY4vNJd7A8</li>
<li>http://www.youtube.com/watch?v=dw1Vh9Yzryo</li>
</ul>
Vid1 is repeated 3 times, Vid2 is repeated 3 times, and Vid3 is repeated 2 times. I want to put them into a structure where I can reference them like this:
youtube[0][repeated] = 3; youtube[0][download] = "http://www.youtube.com/get_video?video_id=dw1Vh9Yzryo&fmt=36"
youtube[1][repeated] = 3; youtube[1][download] = "http://www.youtube.com/get_video?video_id=bOF3o8B292U&fmt=36"
youtube[2][repeated] = 3; youtube[2][download] = "http://www.youtube.com/get_video?video_id=yAY4vNJd7A8&fmt=36"
"This video was repeated " + youtube[0][repeated] + " times and you can download it here: " + youtube[0][download];
How can I set th开发者_JAVA技巧is multidimensional array up? Been Googling for hours and I don't know how to set it up. Can anyone help me out?
Take a look at JQuery: Remove duplicate elements?.
var seen = {};
$('li').each(function() {
var txt = $(this).text();
if (seen[txt])
seen[txt] += 1;
else
seen[txt] = 1;
});
Now seen
looks like
{ "http://www.youtube.com/watch?v=dw1Vh9Yzryo": 3,
"http://www.youtube.com/watch?v=yAY4vNJd7A8": 2,
[...]
}
You can then create a new list:
newlist = $('<ul />');
for (var vid in seen) {
$("<li>This video was repeated " + seen[vid] + " times and you can download it here: " + vid + "</li>").appendTo(newlist);
}
newlist.appendTo(document.body); // or wherever you want it
You can see this working on http://jsfiddle.net/CqMcY/
Okay, I've figured this out. The structure I needed was achieved by using an Object Literal
var youtube = {};
function makeDLLink(video)
{
return "*Download Link*";
}
$('li').each(function() {
var videoLink = $(this).text();
var download = makeDLLink(videoLink);
if (!youtube[videoLink])
{
youtube[videoLink] = { "repeated": 1, "download": download };
}
else
{
youtube[videoLink].repeated += 1;
}
});
$('ul').append("<br /><br /><br />");
for (var key in youtube)
{
var obj = youtube[key];
$('ul').append(key + " was repeated " + obj.repeated + " times and can be DL'd from " + obj.download + "<br /><br />");
}
You can see it in action over at jsFiddle.
精彩评论