4

How to append an object to a Javascript JSON object

I have a javascript object, which contains JSON in the form of an array of objects, such as:

columnDefs: [
  { name: 'Report', field: 'RPT', width: 80 },
  { name: 'Element', field: 'ELEM', width: 200 },
  ...
]

I need to add

cellClass: myFunction 

to each individual column def in the columnDefs array of objects, so it is like:

columnDefs: [
  { name: 'Report', field: 'RPT', width: 80, cellClass: myFunction },
  { name: 'Element', field: 'ELEM', width: 200, cellClass: myFunction  },
  ...
]

Note that myFunction should not be encased in quotes. Since each column def is an object, and 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 what is needed:

[    { name: 'Report', field: 'RPT', width: 80 },  { cellClass: myFunction } ]

There must be an easier and better way to do this?

4 Answers 4

3

Try:

columnDefs.forEach(function(obj) {
   obj.cellClass = myFunction;
});
Sign up to request clarification or add additional context in comments.

Comments

2

You might be misguided about what in does: it already iterates the key of an object (or the indexes of an array).

What you want instead is to parse your json string once, alter it in a loop, then re-serialize it:

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

Comments

0

Is map what you need? Map returns a new array based on transforming the old one.

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

Comments

0
var keys = Object.keys( columnDefs );
keys.forEach(function(item){
  var col = columnDefs[item]
  col['cellClass'] = myFunction
}

2 Comments

There's no reason to use Object.keys here, is there?
Every one in colDefs[key] = colArray; is undefined

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.