【发布时间】:2014-11-28 12:05:25
【问题描述】:
我有一个数组中的对象列表
var myLevel = ['sub', 'topic', 'type'];
var myCollection = new Array();
myCollection.push({sub: 'Book 1', topic: 'topic 1', type: 'mcq'});
myCollection.push({sub: 'Book 1', topic: 'topic 1', type: 'mcq'});
myCollection.push({sub: 'Book 1', type: 'fib', topic: 'topic 2'});
myCollection.push({sub: 'Book 1', topic: 'topic 1', type: 'mtf'});
myCollection.push({sub: 'Book 1', topic: 'topic 1', type: 'mcq'});
myCollection.push({sub: 'Book 2', type: 'mcq', topic: 'topic 1'});
myCollection.push({sub: 'Book 2', topic: 'topic 1', type: 'mcq'});
myCollection.push({sub: 'Book 2', topic: 'topic 1', type: 'mcq'});
我想用 ul 和 li 将这些东西转换成适当的列表,列表的级别也取决于 myLevel 变量。
- 书 1
- 主题 1
- mcq
- mtf
- 主题 2
- 纤维
- 主题 1
- 书 2
- 主题 1
- mcq
- 主题 1
每个部分都有一个唯一的孩子,没有重复的孩子。
我尝试了这段代码,但它会生成重复的孩子
var dom="<ul>";
var used = new Array();
var currentItems = new Array(myLevel.length);
var lastJ = -1;
for(var i=0; i<myCollection.length; i++)
{
var con = false;
for(var k=0; k<used.length; k++){
if(compareObjects(used[k], myCollection[i]))
con = true;
}
if(!con){
for(var j=0; j<myLevel.length; j++){
if(currentItems[j] !== myCollection[i][myLevel[j]]){
if(lastJ !== -1){
for(var l=0; l<lastJ-j; l++){
dom+="</ul></li>";
}
}
for(var l=j+1; l<currentItems.length; l++)
currentItems[l] = "";
currentItems[j] = myCollection[i][myLevel[j]];
dom+="<li>"+currentItems[j]+(j<myLevel.length-1?"<ul>":"");
lastJ = j;
}
}
used.push(myCollection[i]);
}
}
dom+="</ul>";
$('body').html(dom);
function compareObjects(obj1, obj2){
if(obj1.length != obj2.length)
return false;
for(var el in obj1){
if(obj2[el] === undefined)
return false;
if(obj1[el] !== obj2[el])
return false;
}
return true;
}
我得到以下结果
- 书 1
- 主题 1
- mcq
- 主题 2
- 纤维
- 主题 1
- mtf
- 主题 1
- 书 2
- 主题 1
- mcq
- 主题 1
这里第 1 册有两个主题 1。这是不正确的。 我只需要 1 个主题 1。主题 1 应该同时具有 mcq 和 mtf。
谢谢
【问题讨论】:
标签: javascript jquery html arrays object