微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何遍历数组/对象并将某些元素添加到 li?

如何解决如何遍历数组/对象并将某些元素添加到 li?

这是我的第一个问题,如果有点含糊,请见谅。我正在学习 JS,并且我已经被一个问题困住了几个小时。我得到了一个对象,并被告知将该对象中的某些对象添加到 ul。

{
"dsl": {  
"DSL-I-100000": {
    "DSL-I-100000": {      // Add this to an li  
        "priority": "1","standard": true,"customer": true,"internet": true,"business": true,"consumer": true,"filename": "DSL-I-100000.json","download": "100","vpCategory": "dsli"  
    }
},"DSL-IP-100000": {  
    "DSL-IP-100000": {    // Add this to an li  
        "priority": "1","phone": true,"filename": "DSL-IP-100000.json","vpCategory": "dslip"
    }
},"DSL-IP-16000": {    
    "DSL-IP-16000": {     // Add this to an li  
        "priority": "1","filename": "DSL-IP-16000.json","download": "16",

我的任务是创建一个列表,其中包含我的导师所说的“元代码”。那将是 '"DSL-I-100000":',"DSL-IP-100000":,"DSL-IP-16000":。解决这个问题的最佳方法是什么?我的JS知识非常有限,所以请像傻子一样解释。提前致谢。

解决方法

只需从 obj.dsl 获取键,并为每个键创建一个 li 元素。

const obj = {
  dsl: {
    "DSL-I-100000": {
      "DSL-I-100000": {
        priority: "1",standard: true,customer: true,internet: true,business: true,consumer: true,filename: "DSL-I-100000.json",download: "100",vpCategory: "dsli",},"DSL-IP-100000": {
      "DSL-IP-100000": {
        priority: "1",phone: true,filename: "DSL-IP-100000.json",vpCategory: "dslip","DSL-IP-16000": {
      "DSL-IP-16000": {
        priority: "1",filename: "DSL-IP-16000.json",download: "16",};

const ul = document.querySelector("ul");

Object.keys(obj.dsl).forEach(k => {
  const li = document.createElement("li");
  li.innerText = k;
  ul.appendChild(li);
})
<ul>
</ul>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。