我想在 2 组中映射我的数据和排序链接:最喜欢的和不喜欢的。对于每个项目,我还需要密钥和名称。
这是html结构:
<ul class="links-favourites"></ul>
<ul class="non-favourite-list">
<li>Rest of your Links
<ul class="non-favourite-inner"></ul>
</li>
</ul>
3 个链接的数据结构 - 2 个收藏夹和 1 个不收藏夹:
[{
"name": "favourite 1",
"key": "WBwLrM7KkF2qbgRn847yLjJD0e0",
"favourite": true
}, {
"name": "favourite2",
"key": "btB3pFs22S_cBvkCCiMTGWQRVUs",
"favourite": true
}, {
"name": "not favourite1",
"key": "jTOdit6iEBZg8OYK9tOqdoeWYRo",
"favourite": false
}]
这是错误的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]);
});