我将值存储在localStorage中,并从localStorage检索它们后将它们转换为数组。
我只想返回唯一值或可能将它们分组,所以没有重复项。我使用_underscore进行循环。
$.get_played_songs = function(){
if (localStorage.getItem("local_songs") === null) {
recent_holder.html('Play some music');
} else {
var StoredPlays = JSON.parse(localStorage.getItem('local_songs'));
var i=0
_.each(StoredPlays, function(value, key){
recent_holder.append("<div class='recently_played_jams' data-recently_played_sid='"+value.sid+"'>"+value.title+"</div>");
});
}
}
控制台记录“值”将返回此值。
Object { title: "Song1", sid: "47" }
Object { title: "Song1", sid: "47" }
Object { title: "Song1", sid: "47" }
Object { title: "Song12", sid: "47" }
Object { title: "Song2", sid: "47" }
Object { title: "Song2", sid: "47" }
Object { title: "Song2", sid: "47" }
所以我想按sid分组。也许一些正则表达式。
_.uniq
使您可以传入一个函数,该函数确定确定唯一性时要看什么,因此,如果是sid
这样,它们就可以唯一:
StoredPlays = _.uniq(StoredPlays, function(play) { return play.sid; });
var StoredPlays = [
{ title: "Song1", sid: "47" },
{ title: "Song1", sid: "47" } ,
{ title: "Song1", sid: "47" },
{ title: "Song12", sid: "47" },
{ title: "Song2", sid: "47" },
{ title: "Song2", sid: "47" },
{ title: "Song2", sid: "47" }
];
StoredPlays = _.uniq(StoredPlays, function(play) { return play.sid; });
snippet.log(JSON.stringify(StoredPlays));
<script src="http://underscorejs.org/underscore.js"></script>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
或者,如果sid
和 title
:
StoredPlays = _.uniq(StoredPlays, function(play) { return play.sid + "/" + play.title; });
var StoredPlays = [
{ title: "Song1", sid: "47" },
{ title: "Song1", sid: "47" } ,
{ title: "Song1", sid: "47" },
{ title: "Song12", sid: "47" },
{ title: "Song2", sid: "47" },
{ title: "Song2", sid: "47" },
{ title: "Song2", sid: "47" }
];
StoredPlays = _.uniq(StoredPlays, function(play) { return play.sid + "/" + play.title; });
snippet.log(JSON.stringify(StoredPlays));
<script src="http://underscorejs.org/underscore.js"></script>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句