简体   繁体   中英

How can I iterate over an array/object and add certain elements to an li?

this is my first question so apologies if it's a little vague. I'm learning JS, and I've been stuck on a problem for several hours. I've been given an object, and told to add certain objects within that object to an 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",  
            "standard": true,
            "customer": true,
            "internet": true,
            "phone": true,
            "business": true,
            "consumer": true,
            "filename": "DSL-IP-100000.json",
            "download": "100",
            "vpCategory": "dslip"
    }
},  
"DSL-IP-16000": {    
    "DSL-IP-16000": {     // Add this to an li  
        "priority": "1",  
            "standard": true,
            "customer": true,
            "internet": true,
            "phone": true,
            "business": true,
            "consumer": true,
            "filename": "DSL-IP-16000.json",
            "download": "16",
            "vpCategory": "dslip"
    }
},

My task is to create a list containing the 'metacode' as my tutor put it. That would be '"DSL-I-100000":',"DSL-IP-100000":, "DSL-IP-16000":. What's the best way to go about this? My JS knowledge is quite limited, so please do explain as though to a simpleton. Thank you in advance.

Simply get the keys from obj.dsl and for every key create a li element.

 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", standard: true, customer: true, internet: true, phone: true, business: true, consumer: true, filename: "DSL-IP-100000.json", download: "100", vpCategory: "dslip", }, }, "DSL-IP-16000": { "DSL-IP-16000": { priority: "1", standard: true, customer: true, internet: true, phone: true, business: true, consumer: true, filename: "DSL-IP-16000.json", download: "16", vpCategory: "dslip", }, }, }, }; const ul = document.querySelector("ul"); Object.keys(obj.dsl).forEach(k => { const li = document.createElement("li"); li.innerText = k; ul.appendChild(li); })
 <ul> </ul>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM