动态创建嵌套列表项

时间:2019-05-21 18:45:40

标签: javascript

获取如下所示的JSON数据。我想使用js动态创建嵌套列表(ul-li)。

[
    {
        "code": "A00",
        "depth": "0",
        "row": [
            {
                "code": "A001",
                "depth": "1",
                "disease": "Cholera due to Vibrio cholerae 01, biovar eltor"
            },
            {
                "code": "A009",
                "depth": "1",
                "disease": "Cholera, unspecified"
            }
        ],
        "disease": "Cholera",
        "title": "a"
    },
    {
        "code": "A01",
        "depth": "0",
        "row": [
          {
              "code": "A0103",
              "depth": "1",
              "disease": "Typhoid pneumonia"
          }
        ],
        "disease": "Typhoid and paratyphoid fevers",
        "title": "a"
    },
    {
        "code": "A010",
        "depth": "0",
        "row": [
            {
                "code": "A0102",
                "depth": "1",
                "disease": "Typhoid fever with heart involvement"
            },
            {
                "code": "A0103",
                "depth": "1",
                "disease": "Typhoid pneumonia"
            },
            {
                "code": "A0104",
                "depth": "1",
                "disease": "Typhoid arthritis"
            },
            {
                "code": "A014",
                "depth": "1",
                "disease": "Paratyphoid fever, unspecified"
            }
        ],
        "disease": "Typhoid fever",
        "title": "b"
    },
    {
        "code": "A02",
        "depth": "0",
        "row": [
            {
                "code": "A020",
                "depth": "1",
                "disease": "Salmonella enteritis"
            },
            {
                "code": "A021",
                "depth": "1",
                "disease": "Salmonella sepsis"
            }
        ],
        "disease": "Other salmonella infections",
        "title": "b"
    },
    {
        "code": "A022",
        "depth": "0",
        "row": [
            {
                "code": "A0221",
                "depth": "1",
                "disease": "Salmonella meningitis"
            },
            {
                "code": "A0224",
                "depth": "1",
                "disease": "Salmonella osteomyelitis"
            },
            {
                "code": "A0225",
                "depth": "1",
                "disease": "Salmonella pyelonephritis"
            },
            {
                "code": "A0229",
                "depth": "1",
                "disease": "Salmonella with other localized infection"
            }
        ],
        "disease": "Localized salmonella infections",
        "title": "c"
    }
]

缩短

json并更改标题以提高可读性。我想要实现类似

a
  Cholera due to Vibrio cholerae 01, biovar eltor
  Cholera due to Vibrio cholerae 01, biovar eltor
  Typhoid pneumonia
b
  Typhoid fever with heart involvement
  ..
具有相同值的

title所有行数据应位于相同的列表标题中。不应重复标题。相反,具有相同标题的对象应该是行(键)数据,如上图所示。

以下是我迄今为止尝试过的

for (let i = 0; i < json.length; i++) {
  let list = document.createElement('li');
  let ulist = document.createElement('ul');
  let span = document.createElement('span');
  span.appendChild(document.createTextNode(json[i].title));
  for (let j = 0; j < json[i].row.length; j++) {
    let nestedList = document.createElement('li');
    span.classList.add('caret');
    list.appendChild(span);
    ulist.classList.add('nested');
    list.appendChild(ulist);
    nestedList.appendChild(document.createTextNode(json[i].row[j].desease));
    ulist.appendChild(nestedList);
  }
  let mainUl = document.getElementById('someId');
  mainUl.appendChild(list)
}

这就是我得到的(样本结果),但没有成功获得期望的结果

a
  xyz
a
  abc
b
  ...
b
  ...

如果需要更多信息,请与我联系,否则我不清楚。 预先感谢

4 个答案:

答案 0 :(得分:1)

这是一种实现方法的示例。

<input list="manual_emails" type="email" name="manual_email_entry" id="manual_email_entry" class="form-control" placeholder="Zadaj email" multiple />
            <datalist id="manual_emails">
             </datalist>

$search_term = $entry_term.split(/[, ]+/).pop();
var json = [
    {
        "code": "A00",
        "depth": "0",
        "row": [
            {
                "code": "A001",
                "depth": "1",
                "disease": "Cholera due to Vibrio cholerae 01, biovar eltor"
            },
            {
                "code": "A009",
                "depth": "1",
                "disease": "Cholera, unspecified"
            }
        ],
        "disease": "Cholera",
        "title": "a"
    },
    {
        "code": "A01",
        "depth": "0",
        "row": [
          {
              "code": "A0103",
              "depth": "1",
              "disease": "Typhoid pneumonia"
          }
        ],
        "disease": "Typhoid and paratyphoid fevers",
        "title": "a"
    },
    {
        "code": "A010",
        "depth": "0",
        "row": [
            {
                "code": "A0102",
                "depth": "1",
                "disease": "Typhoid fever with heart involvement"
            },
            {
                "code": "A0103",
                "depth": "1",
                "disease": "Typhoid pneumonia"
            },
            {
                "code": "A0104",
                "depth": "1",
                "disease": "Typhoid arthritis"
            },
            {
                "code": "A014",
                "depth": "1",
                "disease": "Paratyphoid fever, unspecified"
            }
        ],
        "disease": "Typhoid fever",
        "title": "b"
    },
    {
        "code": "A02",
        "depth": "0",
        "row": [
            {
                "code": "A020",
                "depth": "1",
                "disease": "Salmonella enteritis"
            },
            {
                "code": "A021",
                "depth": "1",
                "disease": "Salmonella sepsis"
            }
        ],
        "disease": "Other salmonella infections",
        "title": "b"
    },
    {
        "code": "A022",
        "depth": "0",
        "row": [
            {
                "code": "A0221",
                "depth": "1",
                "disease": "Salmonella meningitis"
            },
            {
                "code": "A0224",
                "depth": "1",
                "disease": "Salmonella osteomyelitis"
            },
            {
                "code": "A0225",
                "depth": "1",
                "disease": "Salmonella pyelonephritis"
            },
            {
                "code": "A0229",
                "depth": "1",
                "disease": "Salmonella with other localized infection"
            }
        ],
        "disease": "Localized salmonella infections",
        "title": "c"
    }
];

function buildList(json) {
	var list = {}
  //Loop over the json object and build our new object
  for(var k in json){
    //Grab the title
  	var group = json[k].title;
    //Check to see if our new title has this key
    if(!(group in list)){
      //If not, initialize it as an array
      list[group] = [];
    } 
    //Add all the row.disease entries to the array
    for(var x in json[k].row){
      list[group].push(json[k].row[x].disease);
    }
  }
  
  //Build the html
  var html = '';
  //Itterate over our new list
  for(var x in list) {
    //Add the title key
    html += '<li>' + x;
    //Check to make sure the array isn't empty
    if(list[x] != []){
      //Add the nested ul
      html += '<ul>';
      //ITterate over the items for this key and add li
      for(var item in list[x]) {
        html += '<li>' + list[x][item] + '</li>';
      };
      //Close the ul
      html += '</ul>';
    }
    //close the li
    html += '</li>';
  }
  $('#main').html(html);
}

buildList(json);

答案 1 :(得分:0)

这是对数据的递归构建,它将支持任何深度。

const data = [
    {
        "code": "A00",
        "depth": "0",
        "row": [
            {
                "code": "A001",
                "depth": "1",
                "disease": "Cholera due to Vibrio cholerae 01, biovar eltor"
            },
            {
                "code": "A009",
                "depth": "1",
                "disease": "Cholera, unspecified"
            }
        ],
        "disease": "Cholera",
        "title": "a"
    },
    {
        "code": "A01",
        "depth": "0",
        "row": [
          {
              "code": "A0103",
              "depth": "1",
              "disease": "Typhoid pneumonia"
          }
        ],
        "disease": "Typhoid and paratyphoid fevers",
        "title": "a"
    },
    {
        "code": "A010",
        "depth": "0",
        "row": [
            {
                "code": "A0102",
                "depth": "1",
                "disease": "Typhoid fever with heart involvement"
            },
            {
                "code": "A0103",
                "depth": "1",
                "disease": "Typhoid pneumonia"
            },
            {
                "code": "A0104",
                "depth": "1",
                "disease": "Typhoid arthritis"
            },
            {
                "code": "A014",
                "depth": "1",
                "disease": "Paratyphoid fever, unspecified"
            }
        ],
        "disease": "Typhoid fever",
        "title": "b"
    },
    {
        "code": "A02",
        "depth": "0",
        "row": [
            {
                "code": "A020",
                "depth": "1",
                "disease": "Salmonella enteritis"
            },
            {
                "code": "A021",
                "depth": "1",
                "disease": "Salmonella sepsis"
            }
        ],
        "disease": "Other salmonella infections",
        "title": "b"
    },
    {
        "code": "A022",
        "depth": "0",
        "row": [
            {
                "code": "A0221",
                "depth": "1",
                "disease": "Salmonella meningitis"
            },
            {
                "code": "A0224",
                "depth": "1",
                "disease": "Salmonella osteomyelitis"
            },
            {
                "code": "A0225",
                "depth": "1",
                "disease": "Salmonella pyelonephritis"
            },
            {
                "code": "A0229",
                "depth": "1",
                "disease": "Salmonella with other localized infection"
            }
        ],
        "disease": "Localized salmonella infections",
        "title": "c"
    }
];

const buildLI = (data) => {
  const li = document.createElement('li');
  const span = document.createElement('span');
  span.innerHTML = `code: ${data.code} - ${data.disease}`;
  li.appendChild(span);
  if(data.row) li.appendChild(buildUL(data.row));
  return li;
};

const buildUL = (data) => {
  const ul = document.createElement('ul');
  data.forEach(d => {
    ul.appendChild(buildLI(d));    
  });
  return ul;
};

document.querySelector('div').appendChild(buildUL(data));
<div></div>

答案 2 :(得分:0)

替代现有答案:如果您希望代码更具可读性,则可以创建一个字符串,然后通过innerHTML将其附加到您的容器中。对于简单任务,更直接,更易于维护。

let html = '';

items.forEach(item => {
    html += `
    <ul>
        <li>${item.code}</li>
            <li>
                <ul>`;

    item.row.forEach(row => {
        html += `<li>${row.disease}</li>`;
    });

    html += `
            </ul>
        </li>
    </ul>`;
});

console.log(html);
document.querySelector('#my-wrapper').innerHTML = html;

答案 3 :(得分:0)

由于您要按标题对顶级列表进行分组,因此需要确保每个标题仅创建一个新的顶级列表。

您可能会发现创建一个跟踪顶层列表元素的对象会更容易。

以下代码(从上面进行了修改)创建一个对象,该对象使用title作为键来跟踪spanulistlist元素。这样可以防止重复的顶级列表。

const json = [{
    "code": "A00",
    "depth": "0",
    "row": [{
        "code": "A001",
        "depth": "1",
        "disease": "Cholera due to Vibrio cholerae 01, biovar eltor"
      },
      {
        "code": "A009",
        "depth": "1",
        "disease": "Cholera, unspecified"
      }
    ],
    "disease": "Cholera",
    "title": "a"
  },
  {
    "code": "A01",
    "depth": "0",
    "row": [{
      "code": "A0103",
      "depth": "1",
      "disease": "Typhoid pneumonia"
    }],
    "disease": "Typhoid and paratyphoid fevers",
    "title": "a"
  },
  {
    "code": "A010",
    "depth": "0",
    "row": [{
        "code": "A0102",
        "depth": "1",
        "disease": "Typhoid fever with heart involvement"
      },
      {
        "code": "A0103",
        "depth": "1",
        "disease": "Typhoid pneumonia"
      },
      {
        "code": "A0104",
        "depth": "1",
        "disease": "Typhoid arthritis"
      },
      {
        "code": "A014",
        "depth": "1",
        "disease": "Paratyphoid fever, unspecified"
      }
    ],
    "disease": "Typhoid fever",
    "title": "b"
  },
  {
    "code": "A02",
    "depth": "0",
    "row": [{
        "code": "A020",
        "depth": "1",
        "disease": "Salmonella enteritis"
      },
      {
        "code": "A021",
        "depth": "1",
        "disease": "Salmonella sepsis"
      }
    ],
    "disease": "Other salmonella infections",
    "title": "b"
  },
  {
    "code": "A022",
    "depth": "0",
    "row": [{
        "code": "A0221",
        "depth": "1",
        "disease": "Salmonella meningitis"
      },
      {
        "code": "A0224",
        "depth": "1",
        "disease": "Salmonella osteomyelitis"
      },
      {
        "code": "A0225",
        "depth": "1",
        "disease": "Salmonella pyelonephritis"
      },
      {
        "code": "A0229",
        "depth": "1",
        "disease": "Salmonella with other localized infection"
      }
    ],
    "disease": "Localized salmonella infections",
    "title": "c"
  }
];

const topLevel = {};
const titleSpan = (title) => {
  const span = document.createElement('span');
  span.appendChild(document.createTextNode(title));
  return span;
};
const li = () => document.createElement('li');
const ul = () => document.createElement('ui')
for (let i = 0; i < json.length; i+=1) {
  const title = json[i].title;
  topLevel[title] = topLevel[title] !== undefined
  ? topLevel[title]
  : { 
    list: li(),
    span: titleSpan(title),
    ulist: ul(),
   };
  const {span, ulist, list} = topLevel[title];
  for (let j = 0; j < json[i].row.length; j+=1) {
    let nestedList = document.createElement('li');
    span.classList.add('caret');
    list.appendChild(span);
    ulist.classList.add('nested');
    list.appendChild(ulist);
    nestedList.appendChild(document.createTextNode(json[i].row[j].disease));
    ulist.appendChild(nestedList);
  }
  let mainUl = document.getElementById('someId');
  mainUl.appendChild(list)
}
<div id="someId"></div>