![](/img/trans.png)
[英]How do I append list items <li> from an Unordered list <ul> between four other Unordered lists based upon their content
[英]How do I populate a UL's list items with values from a JSON without creating dupliates?
我有這樣的JSON格式的數據:
[
{ year: 2012, name: "Foo"},
{ year: 2011, name: "Foobar"},
{ year: 2010, name: "Foobar again"},
{ year: 2012, name: "Baz"}
]
有時JSON中會重復一年。 我想構建一個導航欄,顯示與選定的每年相對應的一些數據。
<nav>
<ul>
<li><a href="#2010">2010</a></li>
<li><a href="#2011">2011</a></li>
<li><a href="#2012">2012</a></li>
<ul>
</nav>
如何以不重復輸入年份且不重復的方式填充導航欄中的列表項?
完整答案如下:
var arr = [
{ year: 2012, name: "Foo"},
{ year: 2011, name: "Foobar"},
{ year: 2010, name: "Foobar again"},
{ year: 2012, name: "Baz"}
];
// map all the years into an array
var years = arr.map(function (el) {
return el.year.toString();
});
// remove all of the duplicates from the array
var deduped = years.filter(function(elem, pos) {
return years.indexOf(elem) == pos;
});
// sort the array
deduped = deduped.sort();
// create a docfrag, append some new options to it
// and append it to the select element
var frag = document.createDocumentFragment();
for (var i = 0, l = deduped.length; i < l; i++) {
var item = document.createElement('li');
var anchor = document.createElement('a');
anchor.href = '#' + deduped[i];
anchor.text = deduped[i];
item.appendChild(anchor);
frag.appendChild(item);
}
var select = document.querySelector('nav ul');
select.appendChild(frag);
您可以先使用JSON.parse(yourJSON);將JSOn轉換為javascript對象列表。 然后,刪除重復項並從新陣列中生成列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.