如何使用JavaScript对象在HTML中呈现嵌套列表?

时间:2017-12-13 19:58:56

标签: javascript html json parsing object

我有一个对象,看起来像这样:



let obj = {
  name: "name1",
  nest: [
    {
      name: "name2",
      nest: [
        {
          name: "name3"
        },
        {
          name: "name4",
          nest: [
            {
              name: "name5",
              nest: [
                {
                  name: "name6"
                }
              ]
            },
            {
              name: "name7"
            },
            {
              name: "name8"
            }
          ]
        }
      ]
    }
  ]
}

let parent = document.querySelector("ul");

function forOf (obj) {
	for (let key in obj) {
		if ( typeof obj[key] === "object" && obj.hasOwnProperty("nest") ) {
			createList(obj[name], obj[key]);
		} else if ( typeof obj[key] !== "object" ) {
			let item = document.createElement("li");
			item.textContent = obj[key];
			parent.appendChild(item);
		} else {
			forOf(obj[key]);
		}
	}
}

function createList(obj, skills) {
	let item = document.createElement("ul");
	item.textContent = obj;
	parent.appendChild(item);
	parent = item;
	forOf(skills);
}

forOf(obj);




我需要渲染嵌套无序列表的树。我解析了我的对象,但我无法以正确的方式呈现它。我无法解决每个嵌套列表的父项问题。也许,你有任何想法如何解决它?

我想得到这样的结果:example

1 个答案:

答案 0 :(得分:3)

您可以使用单个循环,仅将定义的键用作值,将nest数组用作子项。



function createList(parent, array) {
    array.forEach(function (o) {
        var li = document.createElement("li"),
            ul;

        li.textContent = o.name;
        parent.appendChild(li);
        if (o.nest) {
            ul = document.createElement("ul");
            li.appendChild(ul);
            createList(ul, o.nest);
        }
    });
}

var  object = { name: "name1", nest: [{ name: "name2", nest: [{ name: "name3" }, { name: "name4", nest: [{ name: "name5", nest: [{ name: "name6" }] }, { name: "name7" }, { name: "name8" }] }] }] }

createList(document.querySelector("ul"), [object]);

<ul></ul>
&#13;
&#13;
&#13;