gpt4 book ai didi

javascript - 如何在javascript中将数据排序到表中?

转载 作者:行者123 更新时间:2023-12-03 01:27:56 24 4
gpt4 key购买 nike

我有这样的数据:

{
"date": "2018-07-01",
"hotel": "Hotel1",
"room": "H1Room1",
"qty": 3
},
{
"date": "2018-07-02",
"hotel": "Hotel1",
"room": "H1Room1",
"qty": 3
},
{
"date": "2018-07-03",
"hotel": "Hotel1",
"room": "H1Room1",
"qty": 2
},
{
"date": "2018-07-01",
"hotel": "Hotel1",
"room": "H1Room2",
"qty": 3
},
{
"date": "2018-07-02",
"hotel": "Hotel1",
"room": "H1Room2",
"qty": 2
},
{
"date": "2018-07-01",
"hotel": "Hotel2",
"room": "H2Room1",
"qty": 2
},
{
"date": "2018-07-02",
"hotel": "Hotel2",
"room": "H2Room1",
"qty": 1
}

我想使用 Javascript 将其放在 table 上。

输出如下:
酒店    |房间       | 2018-07-01 | 2018-07-02 | 2018-07-03
酒店1 |H1房间1| 3                  | 3                 | 2
酒店1 |H1房间2| 2                  | 1
hotel2  |H2Room1| 2                  | 1

如果可能的话使用for循环。

最佳答案

var HotelDetails = [{
"date": "2018-07-01",
"hotel": "Hotel1",
"room": "H1Room1",
"qty": 3
},
{
"date": "2018-07-02",
"hotel": "Hotel1",
"room": "H1Room1",
"qty": 3
},
{
"date": "2018-07-03",
"hotel": "Hotel1",
"room": "H1Room1",
"qty": 2
},
{
"date": "2018-07-01",
"hotel": "Hotel1",
"room": "H1Room2",
"qty": 3
},
{
"date": "2018-07-02",
"hotel": "Hotel1",
"room": "H1Room2",
"qty": 2
},
{
"date": "2018-07-01",
"hotel": "Hotel2",
"room": "H2Room1",
"qty": 2
},
{
"date": "2018-07-02",
"hotel": "Hotel2",
"room": "H2Room1",
"qty": 1
}]

$(document).ready(function(){
CreateHTMLTable();
});

var DateArray = [];

function CreateHTMLTable()
{
var ResultHTML = "<table class='table'><tr>";
var TableHeader = "<th>Hotel</th><th>Room</th>";
var TableRow = "";
for(var k in HotelDetails)
{
if(HotelDetails[k].date != "" && !CheckDateArray(HotelDetails[k].date))
{
TableHeader += "<th>" + HotelDetails[k].date + "</th>";
DateArray.push(HotelDetails[k].date);
}
}

ResultHTML += TableHeader + TableRow + "</tr><table>";
$('#Hotel_Details').append(ResultHTML);
}

function CheckDateArray(datestr)
{
if(DateArray.indexOf(datestr) > -1)
return true;
else
return false;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div id="Hotel_Details"></div>

关于javascript - 如何在javascript中将数据排序到表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51435810/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com