简体   繁体   中英

JSON Output in Javascript to HTML

I have a JSON output as below

{
   "556520000":{
      "lmin":"35",
      "dm":[
         {
            "Width":"147"
         },
         {
            "Depth":"10"
         },
         {
            "Height":"137"
         }
      ],
      "lmax":"68",
   }
}

I'm trying to output the dm key, into html so I get something like

<span id="sku_DM">
<ul>
<li><span>A</span> Width: 147</li>
<li><span>B</span> Depth: 10</li>
<li><span>C</span> Height: 137</li>
</ul>
</span>

The JS I have so far outputs to console ok, but when I try and to output as HTML in ID #sku_DM it just puts the last value rather than what I have in the console. My JS code is below

var SKU = "556520000";
var dimBreak = obj[SKU]["dm"];
for(var i = 0; i < dimBreak.length; i++){
    const dimAll = dimBreak[i];
    let entries = Object.entries(dimAll);
    
    for(const [prop, val] of entries) {
        console.log(prop, val);
        var fullDimensions = (prop, val);
        document.getElementById("sku_DM").innerHTML = fullDimensions;
    }
}

Would appreciate some help on this. Thanks

You could map over the dimBreak array and create the required html markup. After that, you can inject the generated html markup in the DOM .

PS As .map() function returns an array, before inserting the generated html string in the DOM , call .join() function on the returned array to combine all the array elements in one string.

 const obj = { "556520000": { "lmin": "35", "dm": [ { "Width": "147" }, { "Depth": "10" }, { "Height": "137" } ], "lmax": "68", } }; var SKU = "556520000"; var dimBreak = obj[SKU]["dm"]; let charCode = 65; // A const html = dimBreak.map(obj => { const [key, value] = Object.entries(obj).flat(); return ` <li> <span>${String.fromCharCode(charCode++)}</span> ${key}: ${value} </li> `; }); const list = document.querySelector('#sku_DM ul'); list.innerHTML = html.join('');
 <span id="sku_DM"> <ul> </ul> </span>

From your words, I understand that you don't need anything fancy nor any type of data manipulation while rendering. Why not use some good-old pre HTML tag?

 const data = { "556520000": { "lmin":"35", "dm":[ { "Width":"147" }, { "Depth":"10" }, { "Height":"137" } ], "lmax":"68", } } const dmset = Object.values(data).map(({ dm }) => dm) document.querySelector('pre').innerHTML = JSON.stringify(dmset, null, 2)
 <pre></pre>

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