How can we consolidate an array of objects containing 6 keys into fewer keys?

Apologies for any confusion caused by the title. As a newcomer to JavaScript, I may not be able to articulate exactly what I am trying to achieve. Hence, I will showcase my code and explain the desired outcome instead.

Here is an array of objects I am working with:

const mi_array = [{
    text: "1st title",
    col2015: 81.8,
    col2016: 86.4,
    col2017: 67.3,
    col2018: 70.8,
    col2019: 67.6
},{
    text: "2nd title",
    col2015: 90.8,
    col2016: 67.4,
    col2017: 39.3,
    col2018: 50.8,
    col2019: 95.6
}];

My desired output should resemble the following:

const new_array = [{
    name: "1st title",
    data: [81.8,86.4,67.3,70.8,67.6]
},{
    name: "2nd title",
    data: [90.8,67.4,39.3,50.8,95.6]
}];

I have been exploring how to achieve this transformation, but the closest solution I found is not quite what I need:

const new_array = [];

mi_array.forEach(value => {
    for (let key in value) {
        new_array.push(value[key]);
    }
});

console.log(new_array);

However, the current output is not as expected:

["1st title", 81.8, 86.4, 67.3, 70.8, 67.6, "2nd title", 90.8, 67.4, 39.3, 50.8, 95.6];

Answer №1

To transform the array, you can utilize the map method to create a new object where the data property consists of the numerical values from the original array.

const myArray=[{title:"1st data",val2015:81.8,val2016:86.4,val2017:67.3,val2018:70.8,val2019:67.6},{title:"2nd data",val2015:90.8,val2016:67.4,val2017:39.3,val2018:50.8,val2019:95.6}];

const result = myArray.map(item => ({
  name: item.title,
  data: Object.values(item).filter(value => typeof value == 'number')
}))

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

Utilizing Ajax to serialize or transfer JSON objects

I have received a Json object and I am looking to extract the data using JavaScript. Specifically, I need help with looping through fields and extracting the data. def For_Sale_Listing(request,id): try: listing = Listing.objects.filter(pk=id) ...

individual elements displayed sequentially within the same block with variable naming

My code caters to both mobile and desktop versions, with the same elements in the FORM. However, only one block of code is visible at a time depending on the screen size, with one set to display: none. <div id="desktop"> <div id="content"> ...

php struggling to access the final element of an array

So I have a PDO statement that looks like this: $sql = "SELECT FD_DATUM_INGEVOERD || ' ' || FT_TIJD_INGEVOERD FROM BANDZENDINGEN WHERE FD_DATUM_INGEVOERD BETWEEN '".$bt."' AND '".$et."' AND FI_GEBRUIKER1='".$uf."&apos ...

Confirming the validity of an email address with Md-chips

Email Validation for MD-Chips Struggling with creating an email validation for md-chips. The current expression I'm using is not working as expected, since the ng-keypress directive is triggered every time I type something. Any suggestions on how to ...

What could be causing my CSS and Bootstrap.css styles not to be implemented on my webpage?

While working on my Ruby on Rails application, I am trying to customize the design to resemble (which can be downloaded from ). However, I am facing an issue where the style sheets are not being applied. I have moved the style sheets from the bootstrap/c ...

What is the process for immediately changing the background color of an input field as soon as text is entered?

I am encountering an issue with the code snippet provided below. My goal is to change the background color of an input field as soon as I start typing something into it. The scenario involves 4 input fields where if the submit button is clicked and any f ...

Perform an Ajax request with JQuery in an HTML document and transfer the response to a different HTML page

This is my first attempt at using AJAX and jQuery to retrieve data from another HTML page. Below is the code I have written: Here is my JavaScript code: <script type="text/javascript> $(document).ready(function() { $('#submit').click( ...

Iterating through images one time and capturing the mouse coordinates for every click made by the user

I have the following code snippet that displays a series of images and I would like to capture the coordinates of each mouse click on these images. Is there a way to send these coordinates to my email at the end of the image loop? Any assistance in achievi ...

Stop span elements from being removed within a `contenteditable` container

I am facing a challenge with an editable div that contains a span element which I would like to prevent users from deleting. My development environment is Vue3. Currently, if the user presses backspace while their cursor is to the right of the span or sel ...

Retrieve a file through a POST request with node.js

Hi everyone, I'm trying to create a "export to excel" functionality in Node.js for a page. By using Chrome DevTools, I discovered that the file is downloaded after a post request, so I need to replicate it. https://i.sstatic.net/aL9SO.png var reques ...

Error message 'MODULE_NOT_FOUND' occurs while executing a Docker application

Although I successfully created a docker image, I am encountering issues when trying to run it. This is the command that I am using for running: docker run coderpc/test-server Displayed below is the error message that appears in the console. Error: Canno ...

Will terminating a Google Cloud Storage stream impact network usage?

As part of my project, I am developing a media server that will serve streamable audio files. To reduce the number of requests to Google Cloud Storage, I have implemented a caching system. However, one issue I've encountered is that Chrome sends two ...

The search functionality in the table is experiencing a glitch where it does not work properly when trying to search with a

I created a simple mini-app with a search bar and a table displaying data. Users can enter keywords in the search bar to filter the data in the table using lodash debounce function for smoother performance. Everything works fine except for one issue - when ...

Leveraging trustAsHTML with an array of object elements

I'm facing a challenge in passing an array of objects from an Angular Controller to the ng-repeat directive. The objects within the array have multiple properties, some of which may contain HTML that needs to be displayed using the ng-repeat. I' ...

Is it possible to modify the CSS injected by an Angular Directive?

Is there a way to override the CSS generated by an Angular directive? Take, for instance, when we apply the sort directive to the material data table. This can result in issues like altering the layout of the column header. Attempting to override the CSS ...

Issue with Angular Material Table: Dragged rows do not drop in the correct position when scrolling

I'm encountering issues with using Angular Material Table along with Drag and Drop CDK and scrolling. While dragging a row and then scrolling, the row does not drop where intended. Additionally, the animation does not follow the scroll correctly. I ...

Tips for resolving state change issues in VUEX

I am facing an issue with making changes to the state while splicing an element from another array without affecting the state itself. To clarify, I want to remove one element from the array arrayWithFilters = [] without altering the state.selected.filte ...

How can I identify when a form has been edited in order to update the database with those changes only?

Currently, I have a form with over 50 fields. While I've successfully implemented functionality for inserting, selecting, and deleting records, I'm struggling with updating a record. Specifically, if a user only updates one or two fields out of t ...

AngularJS - one-time execution of view generation from .NET controller

Currently, I have an MVC .NET application integrated with AngularJS. In my route provider configuration, I am utilizing the controllers of MVC to retrieve the views as shown below: .when('/Units', { templateUrl: 'Unit/Units' ...

What is the best way to find an onmouseover element with Selenium in Python?

I've been attempting to scrape a website and encountered an element that reveals information in a bubble when the mouse hovers over it. I am using Selenium for web scraping, but I am unsure how to locate this specific element. After examining the pag ...