Reputation: 75
I have an object that is structured like below and I was wondering how I could make it so cost and title become the column headers of the datatable while the values become the rows for each column? For example in the cost column, the rows would be 2500000, 1500000, and 15000000, and in the corresponding title column the rows would be title0, title1, and title2.
{cost:{0:2500000, 1:1500000, 2:1500000}, title:{0:"title0",1:"title1",2:"title2"}}
Upvotes: 1
Views: 348
Reputation: 1450
const data = {
cost: { 0: 2500000, 1: 1500000, 2: 1500000 },
title: { 0: "title0", 1: "title1", 2: "title2" },
};
$(document).ready(function () {
let table = $("#table_id").DataTable({
columns: [...Object.keys(data).map((i) => ({ title: i }))],
"order": [[ 1, "asc" ]]
});
let preparedData = Object.entries(data)
.map(([key, value]) => Object.entries(value).map(([k, v]) => v))
.reduce((a, b) => {
return a.length ? a.map((v, i) => [...v, b[i]]) : b.map((v) => [v]);
}, []);
table.rows.add(preparedData).draw()
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.23/js/jquery.dataTables.js"></script>
<link href="https://cdn.datatables.net/1.10.23/css/jquery.dataTables.css" rel="stylesheet"/>
<table id="table_id" class="display" style="width:100%"></table>
Upvotes: 2