How to add an object to a Javascript JSON object

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?

+4
source share
4 answers

Try:

columnDefs.forEach(function(obj) {
   obj.cellClass = myFunction;
});
+3

, , in: ( ).

json- , , :

var json = "...."; // your json input
var columnDefs = JSON.parse(json);
for (var i in columnDefs) { // columnDefs is an array, i the index
  var row = columnDefs[i];  // index into columnDefs to get the object
  row.cellClass = myFn(row);
}
var newJson = JSON.stringify(columnDefs); // your json output – skip this step if not needed
+2
var keys = Object.keys( columnDefs );
keys.forEach(function(item){
  var col = columnDefs[item]
  col['cellClass'] = myFunction
}
0
source

Is the card what you need? The map returns a new array based on the conversion of the old.

var arr = [
  { name: 'Report', field: 'RPT', width: 80 },
  { name: 'Element', field: 'ELEM', width: 200 }
].map(function(element) {
  element.cellClass = myFunction;
  return element;
});
0
source

Source: https://habr.com/ru/post/1626885/


All Articles