I would like to map my data and sort links in 2 groups: favourite and non favourite . For each item I need key and name as well.
here is the html structure:
<ul class="links-favourites"></ul>
<ul class="non-favourite-list">
<li>Rest of your Links
<ul class="non-favourite-inner"></ul>
</li>
</ul>
Data structure for 3 links - 2 favourites and 1 non-favourite:
[{
"name": "favourite 1",
"key": "WBwLrM7KkF2qbgRn847yLjJD0e0",
"favourite": true
}, {
"name": "favourite2",
"key": "btB3pFs22S_cBvkCCiMTGWQRVUs",
"favourite": true
}, {
"name": "not favourite1",
"key": "jTOdit6iEBZg8OYK9tOqdoeWYRo",
"favourite": false
}]
Here is by buggy JS:
$.post("http://0.0.0.0:9292/api/stremes", function (data) {
var names = data.map(function (i) {
return i['streme'].name
});
var keys = data.map(function (i) {
return i['streme']['key']
});
var favourites = data.map(function (i) {
return i['streme']['favourite']
});
var containerFavourite = document.querySelector(".streme-favorites");
var containerNoFavourite = document.querySelector(".non-favourite-inner");
names.forEach(function (name) {
var li = document.createElement('li');
li.innerHTML = name;
$(li).addClass("name");
$(li).each(function (index) {
$(this).data("favourite", favourites[index]);
console.log(favourites[index]); // giving undefined
});
if ($(li).data("favourite", favourite[index]) == true) {
$(this).addClass("favourite");
containerFavourite.appendChild($(this));
} else {
$(this).addClass("no-favourite");
containerNoFavourite.appendChild($(this));
}
});
$(".name").each(function (index) {
$(this).data("key", keys[index]);
});
why not iterate data
? ie data.forEach(function(e){...})
you can get more information inside the block,and map
s are not necessary.
The complete code would be like:
data.forEach(function(e){
var name = e['streme']['name'];
var favourite = e['streme']['favourite'];
if(favourite){
//...
}else{
//...
}
})
Here's a much cleaner looking solution
var $lists={ 'fav': $('.links-favourites'), 'noFav' : $('.non-favourite-inner') };
$.each(data, function( idx, item){
var isFav= item.favourite;
var list= isFav ? 'fav' : 'noFav';
$lists[list].append( createLI( item, isFav) );
});
function createLI( obj, isFav){
var favClass= isFav ?'favourite' : 'no-favourite';
var elemData={'favourite': obj, 'key': obj.key};
return $('<li>',{ class: favClass}).data( elemData ).text( obj.name);
}
Some of your code is a bit confusing in that data doesn't match stremes
and classes are slightly different in script than in html. But this should give you a good starting point. Also not sure what to do with key
in markup, or what links are supposed to be
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.