Is there a way to convert an array of objects with 2 elements into 2 separate arrays?

I am looking to split a single array containing objects with 2 elements into two separate arrays.

After making an axios call, I received the following array:

chartdata: Array [4]
  [{"total":3,"month":9},
   {"total":5,"month":5},
   {"total":9,"month:"2},
   {"total":4,"month:"1}]

How do I extract an array of totals and an array of months from this data structure?

Answer №1

This solution may be considered a bit more elaborate compared to the other suggestions provided. However, it is important to note that while this method might not be the most efficient in terms of performance, it can still serve its purpose effectively. For tasks where performance plays a crucial role, opting for the map solutions suggested by others would be recommended.

// Here's an example using your array.
const chartdata = [
  {"total":3,"month":9},
  {"total":5,"month":5},
  {"total":9,"month":2},
  {"total":4,"month":1}
];

// Utilizing reduce method to extract totals and months.
const [totals, months] = chartdata.reduce((current, next) => {
  return [
    current[0].concat(next.total),
    current[1].concat(next.month)
  ];
}, [[], []]);

console.log('Totals:', totals);
console.log('Months:', months);

Answer №2

Implement the native JavaScript function map two times

outputs = data.map(function(entry){ return entry.output})
categories = data.map(function(entry){ return entry.category})

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

Organizing multiple <image> tags into an array with Javascript - a beginner's guide!

My HTML file contains multiple images. When a user clicks on them, their IDs should be captured without any issues. I am looking for help with the following tasks: 1) Storing all clicked image IDs in an array For example: array = img01 ; array = img ...

Using Vue/Nuxt.js to compute the cumulative sum of hierarchically structured JSON data

When using Nuxt async data, I am retrieving a JSON object that includes a nested array in the following structure: "topic_list": { "topics": [ { "id": 9148, "title": "A", "views": 12 }, { "id": 3228, ...

A div positioned in front of a centrally-located div

Managing a website with numerous headlines can be a challenge. When a user clicks on a headline, a button located 10px to the left of the headline should appear. However, the catch is that the headlines must always remain centered, regardless of whether th ...

Dynamic v-model for a group in Vue2

I am currently working on a housing form and I have encountered a roadblock that I need assistance with. Essentially, when a user selects that their house has 2 floors in the form, they are then prompted to input the number of rooms, toilets, balconies, et ...

Multiple CSS styles are being employed simultaneously to render the webpage

Currently, I am utilizing JavaScript to choose different CSS styles for various accessibility options such as black on white text and larger text. The issue I am facing arises when switching the CSS sheet, as elements from previously selected sheets are st ...

Issue with AngularJS ng-if causing hidden elements to not respond to ng-select event

In my code, there is a hidden select input that is initially hidden using ng-if. Inside this hidden select, I have included a ng-change tag, which triggers a function to display an img element that is also hidden by ng-if. The element hiddenNinja is hidd ...

Creating a preview of a document with client-side scripting

I have been developing a feature that requires generating a preview in a popup for various file formats including PDF, Word, and Excel. I was able to achieve this by converting the files using Aspose.Words and Aspose.Cells. Here is the code snippet: publ ...

Access within the identical window (PHP file) as opposed to an Iframe

I am currently working with a PHP file that retrieves data from my database. <?php $cdb = new PDO('mysql:dbname=xxx;host=localhost', 'xxx', 'xxx'); foreach ($cdb->query("SELECT * FROM images ORDER BY posted DESC LIMIT ...

AngularJS - choosing the ng-model's index value

I'm looking to retrieve the selected item(s) from a select control along with their values or titles. Once the user has made their selections from the dropdown menu, I want to be able to determine the number of items selected and display their titles ...

What could be causing this minimal Angular - WebTorrent configuration to fail?

The setup appears to be quite straightforward. Check out the Webtorrent usage reference here This is how I have my setup: import WebTorrent from 'webtorrent'; @Component({ selector: 'app-root', standalone: true, template: `bla` ...

I'm experiencing very slow page load times in dev mode with Next.js (30s+). What could be the reason behind this sluggishness?

QUESTION: Encountering a similar issue (but with different files): https://github.com/vercel/next.js/discussions/17977 I've already tried all the suggestions provided in that discussion. This is what the page load process looks like in development ...

I'm struggling to figure out why I can't set an object value to a specific variable in Nightwatch.js

Currently, I am in the process of creating a test script using Nightwatch.js. Before clicking on an element, I am extracting the text within it and isolating the value field to assign it to an externally declared variable. However, I am encountering an iss ...

Is having an excessive amount of reactive data in Vue.js detrimental to app speed and overall performance?

Our team is currently in the process of developing a highly intricate single page application similar to Excel using vue.js. This project consists of over 10,000 components, with each cell functioning as an individual component containing approximately 100 ...

Trying out the ClientPortal in Next.JS with Jest Testing

I'm currently working with NextJS and I want to run tests on the ClientPortal component. My testing toolkit consists of Jest and React Testing Library. Below is a sample code snippet for the ClientPortal component: import { useEffect, useRef, useStat ...

The Angular directive ng-model is not able to return a value

I'm currently troubleshooting an issue with the filters in an older project. Here's the HTML snippet: <input type="text" class="form-control" ng-model="FilterEventsEdit" ng-change="FilterEvents()" ...

I am encountering an issue where the useState hook is returning an undefined value on separate components, even after

When setting up a login context, I wrap all my routes with the context provider and pass the initial value using useState: <userContext.Provider value={{loggedUser, setLoggedUser}}> In LogInMenu.jsx, which is responsible for setting the loggedUser ( ...

Error: Unable to assign value to '18dit075' property as it is not defined in Node.js

var id = req.query.id; var username = req.query.name; var password = req.query.password; console.log(req.query); var data = { people:{ } } data.people[id] = { username: username, password: password, ...

Transmit console log data to a PHP webpage

Is there a way to pass the values collected from a Bootstrap table using console.log to a URL via POST method upon button click? var $table = $('#table'); var $button = $('#button'); function getRowSelections() { re ...

Error in AngularJS: $injector:unpr Provider Not Found

I am currently in the process of creating my own service using the factory methodology as outlined in the documentation. However, I seem to be encountering an issue with an unknown provider error. Below is the code for my app which includes the declaration ...

Performance problem with 'Point-along-path' d3 visualization

I recently explored a d3 visualization where a point moves along a path, following the code example provided at https://bl.ocks.org/mbostock/1705868. During this movement, I observed that the CPU usage ranges from 7 to 11%. In my current project, there ar ...