在动态表格javascript中显示对象数组

VV

我想使用JavaScript在动态表格中显示对象数组。

var rows=[{ name : "John", age:20, email: "[email protected]"},
    { name : "Jack", age:50, email: "[email protected]"},
    { name : "Son", age:45, email: "[email protected]"}
........................etc
   ];

这就是它的外观。我想知道如何将其显示为动态表格。

Prashant Ghimire

这是您的操作方式:

JavaScript解决方案:

内容

var rows = [{
    name: "John",
    age: 20,
    email: "[email protected]"
}, {
    name: "Jack",
    age: 50,
    email: "[email protected]"
}, {
    name: "Son",
    age: 45,
    email: "[email protected]"
}];

var html = "<table border='1|1'>";
for (var i = 0; i < rows.length; i++) {
    html+="<tr>";
    html+="<td>"+rows[i].name+"</td>";
    html+="<td>"+rows[i].age+"</td>";
    html+="<td>"+rows[i].email+"</td>";
    
    html+="</tr>";

}
html+="</table>";
document.getElementById("box").innerHTML = html;

jQuery解决方案:

小提琴

var rows = [{
        name: "John",
        age: 20,
        email: "[email protected]"
    }, {
        name: "Jack",
        age: 50,
        email: "[email protected]"
    }, {
        name: "Son",
        age: 45,
        email: "[email protected]"
    }];

$(document).ready(function () {
    var html = "<table border='1|1'>";
    for (var i = 0; i < rows.length; i++) {
        html+="<tr>";
        html+="<td>"+rows[i].name+"</td>";
        html+="<td>"+rows[i].age+"</td>";
        html+="<td>"+rows[i].email+"</td>";
        
        html+="</tr>";

    }
    html+="</table>";
    $("div").html(html);
});

jQuery解决方案2:

小提琴

var rows = [{
  name: "John",
  age: 20,
  email: "[email protected]"
}, {
  name: "Jack",
  age: 50,
  email: "[email protected]"
}, {
  name: "Son",
  age: 45,
  email: "[email protected]"
}];

const Array2Table = (arr) => {
  let Table = [];
  let top_row = [];
  let rows = [];

  for (let i = 0; i < arr.length; i++) {
    let cells = [];

    for (let property in arr[i]) {
      if (top_row.length < Object.keys(arr[i]).length) {
        top_row.push(`<th scope="col">${property}</th>`);
      }
      if (arr[i][property] === null) {
        cells.push(`<td>${null}</td>`);
      } else {
        cells.push(`<td>${arr[i][property]}</td>`);
      }
    }

    rows.push(`<tr>${cells.join("")}</tr>`);
  }

  Table.push(`<table class="table card-table table-striped">`);
  Table.push(`<thead>${top_row.join("")}</thead>`);
  Table.push(`<tbody>${rows.join("")}<tbody>`);
  Table.push("</table>");
  return Table.join("");
}

$(function() {
  let html = Array2Table(rows);
  $("div").html(html);
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章