我将值存储在 localStorage 中,并在从 localStorage 检索它们后将它们转换为数组。
我只想返回唯一值或可能将它们分组,这样就不会出现重复项。我使用_下划线作为循环。
$.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>
关于jquery - Javascript,从每个循环中获取唯一值或按 value.id 进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27184085/