Is there a more efficient method to gather properties from an object into separate arrays without the need for using `map` twice?

Currently, my code block looks like this:

res.json({
    dates: rows.map(function (item) { return item.Date }),
    counts: rows.map(function (item) { return item.NewMembers })
});

While functional, I can't help but feel it is inefficient as the rows array is being iterated twice. How can I optimize this process and enhance performance by avoiding duplicate iterations?

It's worth noting that this code is built using Express, and res.json represents the response within the route.

If there are improved methodologies available in ES6 to address this issue, I have access to them.

Answer №1

let data={dates:[],counts:[]}   
 rows.forEach(element => {
 data.dates.push(element.Date);
 data.counts.push(element.newMembers);

 });
res.json(data);

Answer №2

One approach is to utilize two arrays for gathering data.

var dates=[], counts = [];

rows.forEach(function (item) { 
    dates.push(item.Date);
    counts.push(item.NewMembers);
});

res.json({
    dates: dates,
    counts: counts
});

Answer №3

One way to tackle this problem is by utilizing the reduce method:

let data = [{date : 'a', member : 'b'}, {date : 'a1', member : 'b1'}, {date : 'a2', member : 'b2'}];

let result = data.reduce( (previous, current) => { 
  previous.date.push(current.date); 
  previous.member.push(current.member); 
  return previous;
}, { date : [], member : [] } );

console.log(result);

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

Integrating Braintree with Angular for accepting Android Pay transactions

Currently facing a challenge with Braintree that I need help resolving. I have successfully set up Braintree to generate my client_token using my API, and created the drop-in feature as a test. Here is how I implemented it: (function () { 'use st ...

Integrate a button following the first paragraph exclusively when there are two or more paragraphs present

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> jQuery(document).ready(function($) { if ( $('p').length < 1 ) { $('p:last-child').after('<div id="toggle" class="btn"> ...

Argument for setInterval function

As a newcomer to programming, I am attempting to develop a basic javascript game. I have encountered an issue with the window.setInterval function and it seems to be causing everything to malfunction. I have been following a tutorial at this link and att ...

The issue of a non-firing Ajax click event in a JavaScript file

I have set up a table in JSP and am attempting to trigger a function when clicking on the table rows to post the data. I created a JavaScript file with an ajax click event, but unfortunately, the event is not being fired. $(document).ready(function( ...

Unable to add files to my JavaScript file

I recently integrated React into an existing project, following the guidelines outlined here: https://reactjs.org/docs/add-react-to-a-website.html. Now, I'm facing an issue where I am unable to import any files (both .js and .css) into my main compone ...

Having trouble with the chaining of AJAX calls using Promises?

I am currently attempting to send a POST request (technically a DELETE) to a php page called delete_post.ajax.php. This request takes data from my AJAX call and utilizes it to delete an item from the database. After deletion, I want my AJAX to then send a ...

Utilizing jQuery.ajax() to retrieve the child div from a separate page

Can anyone help me figure out how to use jQuery ajax() to load two children contents from an external page? I want a pre-loader to display before the main content loads. Below is the code snippet that I have tried. $.ajax({ url: 'notification.htm ...

Encountering issues with displaying images in React Next.js when utilizing dangerouslySetInnerHtml

While working on creating a simple WYSIWYG editor in nextjs, I encountered an issue with displaying uploaded images on the screen. When generating a blob URL for the image and using it as the src attribute of the image tag, it worked fine unless dangerousl ...

Sending a variable using the onchange function in jQuery

I have written a script to toggle the visibility of different divs based on selection var folder; $(function() { $('#teamleag').change(function() { if ($('#teamleag').val() == 'footballal') { $('# ...

Adjust the information within the jwt payload

In my app, I am utilizing passport.js along with jwt for user authentication. The jwt token is signed using a payload that includes various fields, one of which is an avatar field to be used throughout the application. I have implemented a feature that all ...

What is the best way to load an ExtJS combobox with a JSON object that includes an array

After retrieving the following JSON from the backend: { "scripts": [ "actions/rss", "actions/db/initDb", "actions/utils/MyFile", "actions/utils/Valid" ], "success": true } The JSON data is stored as follows: t ...

Designing a unique shape geometry using THREE JS

I've been struggling to replicate an existing city in a 3D environment using THREE.js. I have coordinates for approximately 1000 buildings, each with a varying number of corners making it impossible to use standard cubeGeometry. I attempted to create ...

Passport - The method req.isAuthenticated() will return true in the /login route following the local strategy, however, it will not return true in the /current-session route after using passport.authenticate

While developing a full-stack app using a PERN stack, I encountered an issue regarding user authentication. Upon successfully logging in by sending a POST request with a username and password to /login, the function isAuthenticated() returns true. However, ...

Issue with React.useEffect not functioning in Express application

I'm having trouble with the state not updating or re-rendering in my code. I've tried logging from inside the useEffect function but nothing seems to happen. Any suggestions on how to make the useEffect work properly? app.js var createError = re ...

Is there a way to use Javascript to determine if a string within a JSON object has been altered?

I am looking for a way to continuously monitor changes in a specific string or date stored in a JSON file. How can I effectively store this value and create a mechanism to compare it for any differences? Any assistance would be highly appreciated. // Ex ...

What is the best way to send the output of a function once the loop has completed?

Within a Node/Express server written in CoffeeScript, I am working on a function that looks like this: @resolveServers = (url, servers, answer) -> result = [] treatServer(url, server, (treatAnswer) -> result.push(treatAnswer) ) for server ...

Executing MongoDB collection operations with array filtering

I am looking to count records based on tags and filter them before including in specific groups // data in database {tags: ['video', 'Alex'], ... }, {tags: ['video', 'John'], ... }, {tags: ['video', 'J ...

How to dynamically set a computed background image in Vue 2

I have several divs that I want to style with backgrounds from values stored in an array. My attempt to set the background overlay for each one by creating a computed property has not been successful: computed: { backgroundImage(url) { let ...

Creating URL Paths in Express$route Generation"

In my upcoming node.js project, I am considering using the Express framework. However, one challenge I have encountered is the lack of URL generation for routes compared to other frameworks like Django, Flask, and Rails. I attempted to find some Connect m ...

Working with MongoDB collections in JavaScript to extract and manipulate array data

I have successfully parsed this array using a for loop You can view the results in the console log below. https://i.sstatic.net/zxBna.png When handling role_code in JavaScript, the following code snippet can be used: for (doctor in data.user.userType){ ...