如何将这个数组数据打印到dom元素中

问题描述 投票:0回答:1

如何用 dom 元素打印这个嵌套数组

let probs = [{
        10 : 62,
        25 : 40,
        50 : 8,
        100 : 5,
        200 : 2,
        300 : 1,
        500 : 1
    },{
        2 : 10,
        5 : 22,
        10 : 25,
        25 : 26,
        50 : 8,
        100 : 5,
        200: 2,
        300: 1,
        500: 1
    },{
        2: 30,
        5: 40,
        10: 45,
        25: 25,
        50: 5,
        100: 3,
        150: 2,
        200: 1,
        250: 1
    },{

        2: 70,
        5: 56,
        10: 43,
        25: 22,
        50: 18,
        100: 20,
        150: 15,
        250: 1,
        500: 2
    },{
        2: 125,
        5: 99,
        10: 108,
        25: 75,
        50: 50,
        100: 11,
        250: 2
    }];
javascript arrays dom nested
1个回答
1
投票

逻辑如下:

let data = [
        {
          10: 62,
          25: 40,
          50: 8,
          100: 5,
          200: 2,
          300: 1,
          500: 1,
        },
        {
          2: 10,
          5: 22,
          10: 25,
          25: 26,
          50: 8,
          100: 5,
          200: 2,
          300: 1,
          500: 1,
        },
        {
          2: 30,
          5: 40,
          10: 45,
          25: 25,
          50: 5,
          100: 3,
          150: 2,
          200: 1,
          250: 1,
        },
      ];

      let domStr = ``;

      for (let elem of data) {
        let temp = Object.entries(elem);
        for (let [key, value] of temp) {
          domStr += `
          Key is <b>${key}</b> & value is  <b>${value}</b>
          <br/>
          `;
        }
        // Here adding horizontal line
        domStr += `<hr/>`;
      }
      
      //function to return HTML element by Id
      let elemById = (id) => document.querySelector(`#${id}`);

      let boxTable = elemById("boxTable");

      //writing domStr inside of div
      boxTable.innerHTML = domStr;
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="boxTable"></div>
  </body>
</html>

© www.soinside.com 2019 - 2024. All rights reserved.