gpt4 book ai didi

javascript - 如何将未嵌套的 JSON 转换为 Javascript(或 Coffeescript)中的嵌套 HTML 列表?

转载 作者:行者123 更新时间:2023-11-29 18:23:48 25 4
gpt4 key购买 nike

我有一些 JSON 数据(简单的对象数组)。

var input= [
{
"cat": "some",
"id": "0"
},
{
"cat": "some",
"id": "1"
},
{
"cat": "some/category",
"id": "2"
},
{
"cat": "some/category/sub",
"id": "3"
},
{
"cat": "some/other",
"id": "4"
},
{
"cat": "some/thing/different",
"id": "5"
},
{
"cat": "some/thing/different",
"id": "6"
},
{
"cat": "yet/another",
"id": "7"
}
]

我想根据类别从中生成嵌套的 html 列表:

  • 一些
    • 0
    • 1
    • 类别
      • 2
        • 3
    • 其他
      • 4
    • 东西
      • 不同
        • 5
        • 6
  • 还没有
    • 另一个
      • 7

我的第一步是使用以下函数创建空的嵌套对象:

createNestedObject = function(base, names) {
var = 0;
var results = [];
while (i < names.length) {
base = base[names[i]] = base[names[i]] || {};
results.push(i++);
}
return results;
}

接下来,我通过拆分“cat”字符串并在循环中推送“ids”来使用数据填充它(例如 some.category.sub.ids.push(7))最终结果是:

var output = 
{
"some": {
"ids": [
"0",
"1"
],
"category": {
"ids": [
"2"
],
"sub": {
"ids": [
"3"
]
}
},
"other": {
"ids": [
"4"
]
},
"thing": {
"different": {
"ids": [
"5",
"6"
]
}
},
"yet": {
"another": {
"ids": [
"7"
]
}
}
}
}

但是,这个结构有点问题,因为我事先不知道键名和嵌套深度。如何根据此处显示的“输出”或“输入”数据生成嵌套的 html 列表?

最佳答案

这个怎么样?

Example

JS

function ToHTML(input){
var html = '<ul>';

for(var key in input){
if(input[key] instanceof Array){
for(var i = 0; i < input[key].length; i++){
html += '<li>' + input[key][i] + '</li>';
}
}else{
html += '<li>' + key + ToHTML(input[key]) + '</li>';
}
}
html += '</ul>';
return html;
}

function ToNestedObject(input){
var i, y, len = input.length, parts, partsLen, obj = {}, prev;
for(i = 0; i < len; i++){
parts = input[i].cat.split('/');
partsLen = parts.length;
prev = obj;
for(y = 0; y < partsLen; y++){
prev[parts[y]] = prev[parts[y]] || {};
prev = prev[parts[y]];
}
if(!prev.ids){
prev.ids = [];
}
prev.ids.push(input[i].id);
}
return obj;
}

var input= [
{
"cat": "some",
"id": "0"
},
{
"cat": "some",
"id": "1"
},
{
"cat": "some/category",
"id": "2"
},
{
"cat": "some/category/sub",
"id": "3"
},
{
"cat": "some/other",
"id": "4"
},
{
"cat": "some/thing/different",
"id": "5"
},
{
"cat": "some/thing/different",
"id": "6"
},
{
"cat": "yet/another",
"id": "7"
}
];

document.getElementById('test').innerHTML = ToHTML(ToNestedObject(input));

HTML

<div id='test'></div>

关于javascript - 如何将未嵌套的 JSON 转换为 Javascript(或 Coffeescript)中的嵌套 HTML 列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15657689/

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