What is the best way to structure JSON data before sending it back?

Utilizing mongodb aggregation with the following sample data:

{
"name": "John wire",
"city": "New York"
},
{
"name": "mike jansen",
"city": "Dubai"
}

...etc

and my aggregation code for returning is as follows:

], function (err, result) {
  if (err) {
    logger.error(req.method + ": " + req.originalUrl + ", message: " + err.message)
    next(createError.InternalServerError())
  }
    
  res.send(result); //this line
});

In addition, I have a function that capitalizes every first word of the field name:

function titleCase(str) {
    var splitStr = str.toLowerCase().split(' ');
    for (var i = 0; i < splitStr.length; i++) {
        // You do not need to check if i is larger than splitStr length, as your for does that for you
        // Assign it back to the array
        splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1);     
    }
    // Directly return the joined string
    return splitStr.join(' '); 
  }

Example: John wire -> John Wire

How can I format the data in result.name before it is returned?

Your input would be greatly appreciated. Thank you.

Answer №1

To implement this functionality, utilize the spread operator which was introduced in ES6:

result.map(obj => ({ ...obj, name: convertToTitleCase(obj.name)}));

If you are working with ES5:

result.map(obj => Object.assign(obj, {name: convertToTitleCase(obj.name)}));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Making a Jquery Ajax Request in Real Time

Is there a way to make sure that the "Test Data" text is only displayed in the console after the book details are fully loaded into vm.books? I am trying to make a synchronous ajax call for this purpose. The code below is not producing the expected result ...

Can one recover a Javascript file from a server?

In Python, I am able to extract Javascript code from an HTML file using the code snippet below. import urllib2, jsbeautifier from bs4 import BeautifulSoup f = urllib2.urlopen("http://www.google.com.ph/") soup = BeautifulSoup(f, "lxml") script_raw = str( ...

Tips for making a multi-dimensional array using jQuery

Is it possible to generate a jQuery layout by using two separate each statements as shown below? arrar [ 'aaa'=>'ccsdfccc', 'bb'=>'aaddsaaaa', '1'=>[ 'three'=>'sdsds& ...

Using CSS to position elements absolutely while also adjusting the width of the div

In one section of my website, I have a specific div structure. This structure consists of two divs stacked on top of each other. The first div is divided into two parts: one part with a width of 63% and another part with a button. Beneath the first div, t ...

Retrieving and securely storing information using fetch() on authenticated REST services

Currently, I have successfully set up a React application that communicates with a REST backend which is built using Python and Flask. The specific functionality I have achieved involves downloading data from a database and saving it as a CSV file through ...

Caution: The React Hook useEffect is missing a required dependency

What is the best way to eliminate the warning "React Hook useEffect has a missing dependency" while developing my code? Here is a snippet of the code that triggers the warning: useEffect(() => { if(inactive){ document.querySelect ...

Guide to automatically inserting text into an html form and submitting it without manual intervention

Currently, I am in the process of a project where my main goal is to design an HTML form for submitting replies. One interesting feature I want to include is an option for users who are feeling lazy to simply click on "auto-generate comment", which will ...

Yesterday Box: Creating and Launching URL with Today's Date via Javascript Bookmarklet

Is it possible to create a simple bookmarklet that generates a URL with the current date and opens it automatically in the browser? This feature could be useful for creating URLs for prefilled forms or implementing something like yesterbox for web-based e ...

Error occurs due to a variable being undefined when passed to a callback function within a

Question about Passing Value to JavaScript Callback Functions: Variable in JavaScript callback functions always gets last value in loop? I'm having trouble passing the value of 'k' to the callback function within the fadeOut method. Her ...

Convert a View to a string and transmit it via Json

Is there a way to transform a View into a string and then pass it through Json? See below for an example: [HttpPost] public ActionResult GetTreeUnit(string id) { int _id = id.ExtractID(); string render ="" ...

Custom range-slider in Angular with flexible min/max values

I am currently working with the angular ui-slider and I am looking to dynamically load the min- and max values for the slider from an external source. This will allow me to set them in a structured way, similar to the following: $scope.minMaxValues = { ...

The "events" module could not be resolved in React-Native

The server encountered an internal error: 500 URL: Body: {"message":"There was an issue resolving the module events from the specified directory. This may be due to a module not existing in the module map or directories listed.","name":"UnableToResolveEr ...

Angular 6: Harnessing the Power of Subject

In my angular applications, I have been utilizing the Subject feature from the rxjs library to create an event emitter. However, upon migrating to Angular 6, I encountered the issue that this module is no longer available. Cannot find module 'rxjs/Su ...

Understanding how to utilize jQuery or prototype to interpret onclick event containing "setLocation(...)" can enhance the functionality

I am dealing with a specific tag: <button onclick="setLocation('http://mysite.com/checkout/cart/add/product/17/')" /> My goal is to trigger an ajax request when the button is clicked. I want to extract the URL segment "product/17" and app ...

Verify if the ajax request does not contain any data

Utilizing the complimentary geocoding API provided by MapQuest I'm attempting to verify the success of a request that returned no data. Entering "vdfsbvdf54vdfd" (a nonsensical string) as an address in a form field, I anticipate receiving an alert s ...

'Nullified' entity utilizing MongoDB and Express

Upon attempting to print the client-side received object on the console using console.log(this.data), I am consistently encountering the issue of getting undefined. This prevents me from being able to access data.body and display the data stored in the dat ...

Establishing a connection between a Google spreadsheet to create and automatically update calendar events

I'm currently working on connecting my Google Sheet to a calendar so that it can automatically generate calendar events and keep them updated based on changes made in the sheet. The Google Sheet I'm using tracks new building opening dates and con ...

Can you explain the role of [Yield, Await, In, Return] in EcmaScript syntax?

EcmaScript production rules often include the use of "modifiers" such as: [Yield, Await, In, Return] Here are a couple of examples: ArrayLiteral[Yield, Await]: ... ElementList[Yield, Await]: ... AssignmentExpression[+In, ?Yield, ?Await] I have look ...

Loading complex JSON data into objects in TypeScript can be a challenging and intricate task

Dealing with a unique JSON structure that needs to be loaded into a TypeScript model. The challenge arises from receiving the JSON as an object instead of an array from a third party source. Is there a method to successfully load this data into the model ...

JavaScript can only append a type that is unique

I need to modify the code below in order to: Show only one input for each unique href inside the .item a (for example, show one input with value img/united-airlines.jpg and another with img/american-airlines.jpg) Display the quantity of each href after t ...