rows().data() is not returning an Array as it is supposed to do

rows().data() is not returning an Array as it is supposed to do

abameerdeenabameerdeen Posts: 1Questions: 1Answers: 0
edited July 2016 in Free community support

I'm using DataTable.js version 1.10.7 in my application. I'm expecting to get an Array of row data that was added to the table after initiation. I have followed steps as in this documentation in says, https://datatables.net/reference/api/rows().data()

// DataTable initiation
var materialsInPurchaseOrder = $("#materials-in-purchase-order").DataTable({
        "dataSrc" : "data",
        "columns": [
            { "data": "MaterialId" },
            { "data": "MaterialName" },
            { "data": "Quantity" },
            { "data": "Cost" }
            ]
    });

// after the document is ready attach two event listeners
$(document).ready(function () {

// adding rows to the table from a form on submission of a form
        $("#create-material-in-purchaseOrder").on("submit", function (event) {
            var data = {};
            data = getFormValues("#create-material-in-purchaseOrder");
            $("#MaterialList option:selected").each(function () {
                data["MaterialName"] = $(this).html();
            });
            
            materialsInPurchaseOrder.row.add(data).draw(false);
            return false;
        });
      
// Processing the DataTable on a button click
        $("#create-purchaseOrder").submit(function (event) {
            var materials = materialsInPurchaseOrder.rows().data();
            console.log('Materials',materials);
            for (var material in materials) {   
            // do something with the row data
            }
            return false;
        });
    });

I get the below output for the console.log() instead of an Array
[Object, context: Array[1], selector: Object, ajax: Object]

Some research I did,
https://jsfiddle.net/5uko1w3q/
http://stackoverflow.com/questions/31932680/jquery-datatables-access-all-rows-data

How can I get an Array of DataTable row data.?

Edited by Allan - Syntax highlighting. Details on how to highlight code using markdown can be found in this guide.

Answers

  • allanallan Posts: 62,301Questions: 1Answers: 10,216 Site admin

    row().data() will return a DataTables API instance as the reference page for that method notes. If you want to convert the API instance into a plain Javascript array, use the toArray() method.

    The DataTables API instance is array-like (just as jQuery is array-like) so you can still iterate over it or otherwise access its elements like an array if you didn't want to convert it to an array.

    Allan

This discussion has been closed.