How to add an object to a JSON Javascript object
I have a javascript object that contains JSON as an array of objects, for example:
columnDefs: [
{ name: 'Report', field: 'RPT', width: 80 },
{ name: 'Element', field: 'ELEM', width: 200 },
...
]
I need to add
cellClass: myFunction
for each individual def column in an array of columnsDefs objects, so it looks like this:
columnDefs: [
{ name: 'Report', field: 'RPT', width: 80, cellClass: myFunction },
{ name: 'Element', field: 'ELEM', width: 200, cellClass: myFunction },
...
]
Note that myFunction should not be quoted. Since each def column is an object, not an array, I understand that I need to convert it to an array before I can add anything to it:
var keys = Object.keys( columnDefs );
for( var key in keys ) {
var col = columnDefs[key]
var colArray = [];
colArray.push( JSON.parse( JSON.stringify( col )));
colArray.push( { cellClass: myFunction } );
colDefs[key] = colArray;
}
However, the above code generates the following, which is not necessary:
[ { name: 'Report', field: 'RPT', width: 80 }, { cellClass: myFunction } ]
Should there be an easier and better way to do this?