1

I have an array of objects below.

   var arrayObjects= [
    {
        "name":       "Tiger Nixon",
        "position":   "System Architect",
        "salary":     "$3,120",
        "start_date": "2011/04/25",
        "office":     "Edinburgh",
        "extn":       "5421"
    },
    {
        "name":       "Garrett Winters",
        "position":   "Director",
        "salary":     "$5,300",
        "start_date": "2011/07/25",
        "office":     "Edinburgh",
        "extn":       "8422"
    }
]

The array is dynamically updated, through some API calls that my app makes.

I instantiate a datatable as shown.The array at this point, the arrayObjects is empty.

HTML
<table id="myTable" class="table table-striped table-dark">
         <thead>
          <tr>
              <th>Name</th>
              <th>Position</th>
              <th>Salary</th>
              <th>Office</th>
          </tr>
      </thead>
    </table>
JAVASCRIPT
var myDataTable=$('#myTable').DataTable( {
    data: arrayObjects,
    columns: [
         { data: 'name' },
         { data: 'position' },
         { data: 'salary' },
         { data: 'office' }
    ]
} );

I add new objects in the array as follows:

EDIT: somedata can be as follows:

var somedata = {
        "name":       "James",
        "position":   "CEO",
        "salary":     "$13,140",
        "start_date": "2017/04/25",
        "office":     "London",
        "extn":       "54211"
    }
arrayObjects.push(somedata);

How do I add data to the table/update the table after that? I have tried:

myDataTable.clear().row.add(arrayObjects).draw();

but it doesn't seem to work. The Table is still empty.

3
  • from where are you getting somedata? Commented Apr 8, 2018 at 14:36
  • Adding a row means passing one row of data each time. When you push someData to array, also add as row then call draw after all rows added Commented Apr 8, 2018 at 14:37
  • @PrashantPokhriyal I have updated the question to be bit clear, I hope that helps. Commented Apr 8, 2018 at 15:06

1 Answer 1

2

The problem is in using row API instead of rows API because you are storing as an array of objects.

Change it to

myDataTable.clear().rows.add(arrayObjects).draw();

Working jsfiddle.


To work with row API you have to change the arrayObjects either as a simple array or single object like below

var arrayObjects = ['James', 'CEO', '$13000', 'London'];
// or
var arrayObjects = {
  "name": "James",
  "position": "CEO",
  "salary": "$13,140",
  "office": "London"
};

// it will work now
myDataTable.clear().row.add(arrayObjects).draw();
Sign up to request clarification or add additional context in comments.

Comments

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.