Reputation: 36227
I am working with handsontable with a php backend. i am tring to dynamically create table column headers so I can create an array of column names which I can feed into handsontable using:
colHeaders: ['ID', 'First', 'Last Name', 'Address'],
I've included a sample of JSON produced at backend in the screenshot. How do I create get the keys so I can create the colHeaders array? i've tried:
var keys = res.keys();
My load function is:
$parent.find('button[name=load]').click(function () {
$.ajax({
url: "AjaxController/tableLoad/"+tablename,
dataType: 'json',
type: 'GET',
success: function (res) {
var keys = res.keys();
console.log(keys);
// create js title array from 1st row data
// colHeaders: ['ID', 'First', 'Last Name', 'Address'],
// handsontable.colHeaders: keys;
handsontable.loadData(res);
$console.text('Data loaded');
console.log(res)
},
Upvotes: 0
Views: 112
Reputation: 24638
You can use .map()
to get the keys of an object as follows:
var keys = $.map(res, function(element,key) { return key; });
However for the sample you've provided, an array of objects, you would use the following:
var keys = $.map(res[0], function(element,key) { return key; });
//RESULT: ["id", "name", "description"]
Upvotes: 1
Reputation: 19700
For a valid JSON
use Object.keys(object),
to get its keys which returns an iterable
object.
var keys = Object.keys(res);
Upvotes: 3