gpt4 book ai didi

javascript - 将对象转换为 ul li 元素

转载 作者:行者123 更新时间:2023-12-03 11:33:35 25 4
gpt4 key购买 nike

我有一个数组中的对象列表

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
      • 谎言
  • 第 2 册
    • 主题 1
      • mcq

每个部分都有一个独特的子项,不能有相同的。

我尝试将元素创建到 myCollection 的循环中

for(var i=0; i<myCollection.length; i++)
{
for(var j=0; j<myLevel.length; j++)
{
createMyTree(myCollection[i][myLevel[j]);
}
}


function createMyTree(str)
{
//?????????????
}

请帮助我如何在所需的级别上创建元素。

最佳答案

好的,所以我重新做了它,它可以工作,除非有一个问题:主题 1 get 被分成两个主题 1,因为主题 2 get 插入在它们之间。

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'});

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;
}

关于javascript - 将对象转换为 ul li 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26628559/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com