我有以下对象:
var object = [
{
"category": "Apple",
"color": "green"
},
{
"category": "Orange",
"color": "Orange"
},
{
"category": "Apple",
"color": "green"
}
];
我正在尝试通过类别迭代数据,因此以下内容将显示在列表中:
下面是我尝试过的代码,但不幸的是它按照它出现在对象中的顺序显示。任何想法都会非常感激。
function makeUL(object) {
var list = document.createElement('ul');
for(var i = 0; i < object.length; i++) {
var item = document.createElement('li');
var a = document.createElement("a");
a.textContent = object[i].category;
a.setAttribute('href', 'http://test');
item.appendChild(a);
list.appendChild(item);
}
return list;
}
答案 0 :(得分:2)
组改变的解决方案:
var object = [{ "category": "Apple", "color": "green" }, { "category": "Orange", "color": "Orange" }, { "category": "Apple", "color": "green" }];
function makeUL(object) {
var div = document.createElement('div');
object.sort(function (a, b) { return a.category.localeCompare(b.category); });
object.forEach(function (aa) {
var a = document.createElement("a"),
item = document.createElement('li'),
p;
if (aa.category !== this.last) {
p = document.createElement('p');
p.innerHTML = aa.category;
div.appendChild(p);
this.list = document.createElement('ul');
div.appendChild(this.list);
this.last = aa.category;
}
a.textContent = aa.category;
a.setAttribute('href', 'http://test');
item.appendChild(a);
this.list.appendChild(item);
}, { last: undefined, list: undefined });
return div;
}
document.body.appendChild(makeUL(object));
&#13;
答案 1 :(得分:0)
如果您希望按字母顺序排序数组(DESC顺序,从A到Z),则必须先调用.sort()
方法
function makeUL(object) {
var list = document.createElement('ul');
object.sort();
for(var i = 0; i < object.length; i++) {
var item = document.createElement('li');
var a = document.createElement("a");
while(i<length - 1 && object[i].category == object[i+1].category)
a.textContent += object[i].color + ", ";
a.setAttribute('href', 'http://test');
item.appendChild(a);
list.appendChild(item);
}
return list;
}
答案 2 :(得分:0)
您可以使用Array.sort
请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
function compare(a, b) {
if (a is less than b by some ordering criterion) {
return -1;
}
if (a is greater than b by the ordering criterion) {
return 1;
}
// a must be equal to b
return 0;
}
答案 3 :(得分:0)
在将数组用于for循环
之前对其进行排序object.sort(function(a,b){
return a.category > b.category
});
答案 4 :(得分:0)
object.sort(function(a, b) {
return a.category > b.category;
});
结果
[ { category: 'Apple', color: 'green' },
{ category: 'Apple', color: 'green' },
{ category: 'Orange', color: 'Orange' } ]