简体   繁体   English

遍历数组中的对象并在JavaScript中创建单独的表

[英]Looping over an objects in a array and create separate tables in JavaScript

Please help me create three different tables based on the region name, each table could have multiple fields based on data from backend. 请帮助我根据区域名称创建三个不同的表,每个表可以基于来自后端的数据包含多个字段。 basically I need to create a title as region name and group all details as per region name. 基本上,我需要创建一个标题作为区域名称,并按照区域名称对所有详细信息进行分组。

For example: 例如:

Title of table: 表格标题:

New York
name | age
bob    26

chicago
name | age
bob    26
mick   25

Here is my array: 这是我的数组:

var details = [
  {
    "region": "chicago",
    "name": "bob",
    "age": 26
  },
  {
    "region": "chicago",
    "name": "mick",
    "age": 25 
  },{
    "region": "new york",
    "name": "tom",
    "age": 21,
    "status": "active"
  },
  {
    "region": "new jersey",
    "name": "gen",
    "age":22  
  },
  {
    "region": "new york",
    "name": "mike",
    "age": 29,
    "hobby": "ps"
  }  
]

If I understand your question correctly, (from the supplied data example) column names can be dynamic, the problem with that is that to construct a table from such data you need to know possible columns ahead, which basically means iterating over data twice. 如果我正确地理解了您的问题,(从提供的数据示例中)列名可以是动态的,那么问题是要从此类数据构造表,您需要知道前面可能的列,这基本上意味着对数据进行两次迭代。

var tables = {}, columns = [];

// first extract all possible column names, excluding region ofcourse
details.forEach((detail) => {
  Object.keys(detail).forEach((column) => {
    if (column !== "region" && columns.indexOf(column) === -1) {
      columns.push(column);
    }
  });
});

// then iterate over data and construct table rows
details.forEach((detail) => {
  var table = tables[detail.region] || (tables[detail.region] = []), row = {};
  columns.forEach((column) => row[column] = detail[column])
  table.push(row);
});

// after data has been grouped into tables just create simple table
// and add data rows.
$.each(tables, (regionName, rows) => {
  var table = $("<table/>");
  var regionNameRow = $("<tr/>");
  var columnsRow = $("<tr/>");
  var regionNameTh = $("<th colspan='" + columns.length + "'>" + regionName + "</td>");


  columns.forEach((column) => {
    columnsRow.append($("<th>").html(column));
  });

  regionNameRow.append(regionNameTh);
  table.append(regionNameRow);
  table.append(columnsRow);

  rows.forEach((row) => {
    var tableRow = $("<tr/>");
    $.each(row, (columnName, value) => {
      tableRow.append($("<td>").html(value || "-"));
    });
    table.append(tableRow);
  });


  $("#container").append(table);
  $("#container").append("<hr/>");
});

Here's a fiddle with the result https://jsfiddle.net/okqbq4r2/18/ 这是结果的小提琴https://jsfiddle.net/okqbq4r2/18/

Also you might need to added additional filtering step if you wish to exclude empty columns. 另外,如果要排除空列,可能还需要添加其他过滤步骤。

You can do something like this tho extract the data 您可以执行以下操作来提取数据

var chicagoList = details.map(function(x) {

  if (x.region === 'chicago') {
      return {
        "name": x.name,
        "age": x.age
      };
    }
  });

So my answer might be a little long winded but you can go through the array, grab the unique regions, create tables dynamically and then append rows based on matching regions. 因此,我的答案可能会有点冗长,但是您可以遍历数组,获取唯一区域,动态创建表,然后根据匹配区域追加行。 Not the most elegant but it will get the job done. 不是最优雅的,但可以完成工作。 Code below and working jsfiddle here https://jsfiddle.net/brockdavis008/b69g3w3p/ 下面的代码和在这里工作的jsfiddle https://jsfiddle.net/brockdavis008/b69g3w3p/

$(function(){
 CreateTables();
})

function CreateTables(){
var uniqueRegions = []
$.each(details,function(index,item){
    if (($.inArray(item.region, uniqueRegions)) == -1){
  uniqueRegions.push(item.region);
  }
})
$.each(uniqueRegions,function(index,item){
var regionname = item.replace(" ","");
$("#data").append("<table id='"+regionname+"region'><th>Name</th><th>Age</th>")
});

$.each(details,function(index,item){
var tr = "<tr><td>"+item.name+"</td><td>"+item.age+"</td></tr>";
var regionname = item.region.replace(" ","");
$("#"+regionname+"region").append(tr)

})
}

var details = [
  {
    "region": "chicago",
    "name": "bob",
    "age": 26
  },
  {
    "region": "chicago",
    "name": "mick",
    "age": 25 
  },{
    "region": "new york",
    "name": "tom",
    "age": 21,
    "status": "active"
  },
  {
    "region": "new jersey",
    "name": "gen",
    "age":22  
  },
  {
    "region": "new york",
    "name": "mike",
    "age": 29,
    "hobby": "ps"
  }  
]

You can reduce the details first into an array that has objects segregated into regions. 您可以先将details缩减为一个数组,该数组将对象划分为多个区域。

 const details = [{ "region": "chicago", "name": "bob", "age": 26 }, { "region": "chicago", "name": "mick", "age": 25 }, { "region": "new york", "name": "tom", "age": 21, "status": "active" }, { "region": "new jersey", "name": "gen", "age": 22 }, { "region": "new york", "name": "mike", "age": 29, "hobby": "ps" }]; const tableDetails = details.reduce((arr, item) => { const isRegionExisting = arr.some((detail) => detail.region === item.region); let region; if (isRegionExisting) { region = arr.find((detail) => detail.region === item.region); } else { region = { region: item.region, people: [] }; arr.push(region); } region.people.push({ name: item.name, age: item.age, }); return arr; }, []); tableDetails.forEach(generateTable); function generateTable({ region, people }) { const table = document.createElement('table'); const caption = table.appendChild(document.createElement('caption')); const thead = table.appendChild(document.createElement('thead')); const theadRow = thead.appendChild(document.createElement('tr')); const tbody = table.appendChild(document.createElement('tbody')); caption.innerText = region; Object.keys(people[0]).forEach((key) => { const th = theadRow.appendChild(document.createElement('th')); th.innerText = key; }); people.forEach((person) => { const tr = tbody.appendChild(document.createElement('tr')); Object.values(person).forEach((value) => { const td = tr.appendChild(document.createElement('td')); td.innerText = value; }); }); document.body.appendChild(table); } 
 * { margin: 0; padding: 0; } body { font: 14px/1.8 normal Helvetica, Arial, sans-serif; } table { border-collapse: collapse; margin: 10px 0; table-layout: fixed; width: 100%; } caption, th { font-weight: 600; text-transform: capitalize; } th, td { padding: 5px; text-align: center; } th { background: #eee; } tbody tr { border-bottom: 1px dotted #eee; } tbody tr:last-child { border-bottom: 0; } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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