While a Javascript array can have custom properties such as you are doing with this line of code:
result['add_key'] = 'abcdd';
JSON.stringify()
(and consequently res.json()
too) will only put actual array elements (not custom properties) in the generated JSON. So, if result
is an array, that is why this property does not show in the generated JSON.
In fact, the JSON text format, only has a place for array elements in the JSON format for an array. There is no place for regular custom properties like your ['add_key
] property. That property would have to be on a plain object for it to show in the JSON.
In the section 7 of the JSON specification where arrays are described,
it clearly shows that the only JSON representation for an array is the
array elements themselves (separated by commas). There is no place for a property name/value pair in the expression for an array.
You did not show exactly what you want the resulting JSON to look like, but there are several other ways you could represent the add_key
property and value. You could move the property to the response
object:
connection.modal.find( { 'id' : '2' }, function ( err, result ) {
var response = {};
response['add_key'] = 'abcdd';
response['success'] = true;
response['result'] = result;
response['msg'] = 'Result fetched';
res.json(response);
});
You could put the result into it's own object and that object could have the add_key
property on it:
connection.modal.find( { 'id' : '2' }, function ( err, result ) {
var response = {};
var resultContainer = {};
resultContainer['add_key'] = 'abcdd';
resultContainer['result'] = result;
response['success'] = true;
response['result'] = resultContainer;
response['msg'] = 'Result fetched';
res.json(response);
});
FYI, you don't have to normally use the bracket syntax for setting properties. You could also do this (which many find a bit cleaner):
connection.modal.find( { 'id' : '2' }, function ( err, result ) {
var response = {};
response.add_key = 'abcdd';
response.success = true;
response.result = result;
response.msg = 'Result fetched';
res.json(response);
});
The only time you have to use the bracket syntax is if the property name is in a string variable or if it contains certain characters that aren't permitted in the dot syntax. For regular alpha characters and a property name that is not in a variable, you can just use the dot syntax.