1

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"}}

1 Answer 1

2

Solution:

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Nice (+1). You can simplify the adding of data by using table.rows.add( preparedData ).draw();, instead of one row at a time with preparedData.forEach(...). You already have an array of arrays. See rows.add().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.