What methods should I use to modify the upcoming array of objects?

I have been struggling with this exercise for about an hour now, and I can't figure it out. Can someone please help me with this?

Here is the array that I retrieved from the database: View Base Array Image

let data = [
{
"name": "October : 2019",
"userName": "Katherine Diaz",
"newCases": 875,
"recover": 8
},
// more data here...
]

I would like to transform the data as follows for testing purposes. Here's a snippet of what I want to achieve: View Transformation Image

let transformedData = [
{
    name: 'October',
    user: ['Katherine Diaz', 'Belyini Cabral', 'Mercedes Perez', 'N/A'],
    newCases: [/* random numbers */],
    recovered: [/* random numbers */],
    monthRecovered: /* random number */,
    monthNewCases: /* random number */
},
// more transformed data here...
];

This seems a bit complex for me at the moment. I believe I need more understanding of data structures in this language. Could someone point me in the right direction and provide some steps to get started? Thank you.

Answer №1

To group objects and extract their values as an array of objects, you can use a specified object for grouping.

var data = [{ name: "October : 2019", user: "Alice Smith", sales: 100, profit: 50 }, { name: "November : 2019", user: "Bob Johnson", sales: 200, profit: 70 }, { name: "December : 2019", user: "Cathy Brown", sales: 150, profit: 30 }],
    result = Object.values(data.reduce((obj, { name, user, sales, profit }) => {
        if (!obj[name]) obj[name] = { name, users: [], salesData: [], profits: [] };
        obj[name].users.push(user);
        obj[name].salesData.push(sales);
        obj[name].profits.push(profit);
        return obj;
    }, {}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

To populate the premiere data, it is necessary to loop through the response array.

var response=... (same as in original post),
    premiere=[],
    keys={};
for(var i=0;i<response.length;i++) {
    var element=response[i];

    //Parsing the element name may be required to remove the year
    var name=element.name;

    //Tracking where each name is located in premiere is crucial
    var index;
    if(!keys.hasOwnProperty(name)) {
        //If the name does not exist, create it and assign values later
        index=premiere.push({
            name:name,
            user:[],
            newCases:[],
            recovered:[],
            monthNewCases:0,
            monthRecovered:0
        })-1;
        //Store the index of the name in keys
        keys[name]=index;
    } else {
        //If the name exists, get its index to append new data
        index=keys[name];
    }      

    //Ensure no duplicates by checking for existing user names
    //Push the user name if it does not already exist
    if(premiere[name].user.indexOf(element.userName)<0) premiere[name].user.push(element.userName);

    premiere[name].newCases.push(element.newCases);
    premiere[name].recovered.push(element.recover);

    //Update the total new cases and recoveries for the month
    premiere[name].monthNewCases+=element.newCases;
    premiere[name].monthRecovered+=element.recover;
}

This code has not been tested yet.

Answer №3

Take a look at Array.reduce method to loop through the response data and construct a new array:

const response = [
  {
    "name": "October : 2019",
    "userName": "Katherine Diaz",
    "newCases": 875,
    "recover": 8
  },
  {
    "name": "December : 2019",
    "userName": "A guy named Jeff",
    "newCases": 503,
    "recover": 380
  },
  {
    "name": "December : 2019",
    "userName": "Patient Zero",
    "newCases": 999,
    "recover": 38
  },
];

const result = response.reduce((acc, item) => {
  // create a new entry for this item's name if it doesn't already exist
  const bin = acc[item.name] = acc[item.name] || { user: [], newCases: [], recovered: [] };

  // add the fields we care about to this entry
  bin.user.push(item.userName);
  bin.newCases.push(item.newCases);
  bin.recovered.push(item.recover);
  
  // return the updated accumulator for the next iteration
  return acc;
}, {})

document.getElementById('output').innerText = JSON.stringify(result, null, 2);
<pre id="output"></pre>

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

Retrieve data from a specific field in a JSON response

I am attempting to retrieve a specific field from an API request, which will be utilized for another task. My goal is to automate this request in order to keep track of the timestamp of the remote machine. Here is the script I have created to obtain the j ...

How can I store unique and only selected checkbox values in an array using Angular?

I need assistance with creating an array from three checkboxes. The array should only contain the values of the checked checkboxes and should not include duplicates. I have attempted to achieve this functionality, but the values are still being added rega ...

Tips for submitting an e-mail through an HTML form with the help of Node.js and Gulp

Today, I've been tackling the challenge of creating an HTML contact form that can send an email using Node.js and Gulp. However, I'm struggling to find a solution. Using a relative path to a simple .PHP file doesn't seem to be working, so it ...

The Bootstrap tooltip fails to function properly following a page update or refresh

My tooltip component seems to be malfunctioning, and I suspect the issue lies within the option attributes. I am unsure where the problem is occurring and how to resolve it. The tooltip component was initialized using the code below: var options = { anim ...

Adding npm packages to your Vue.js application

My Vue app is structured like this (auto created by vue init webpack myProject): index.html components/ -main.js -App.vue I am trying to include npm packages, such as https://github.com/ACollectionOfAtoms/atomic-bohr-model. Following the instructions, I ...

Experimenting with a custom AngularJS filter designed to extract numerical values from a chunk of text

I am working on creating a unique filter that can extract numbers from text input into a text box. For example: User enters: The cat went to 4 stores and bought 3 bags of cat litter for 1 dollar. The desired output would be: [4, 3, 1] This filter works ...

issue with for loop in jquery ajax not processing complete response data

I have a total of 9 columns in my table, namely choosen_emails_1, choosen_emails_2, choosen_emails_3, booking_address, booking_number, booking_message, booking_date, request_date & user_email The for loop is programmed to iterate and display all colum ...

Tips for converting data to JSON format without the need for an object

I am looking to convert my variables to JSON for the purpose of POSTing the JSON to an external API. I do not want to create a separate model just for serialization of these values. Using a Dictionary is not feasible as the structure is unconventional, su ...

What is the process for converting plain text into an image tag using the methods ".replace()" and ".html()"?

My goal is to customize this particular answer so that it can transform classic BCCode [img]{url}[/img] into an HTML image. In the code snippet provided, I have successfully implemented something similar with [b]text[/b]. However, when attempting to use [i ...

Replicating JavaScript functions with the power of Ajax

I'm facing an issue with Bootstrap modal windows on my page. The modals are opening and closing successfully, but the content inside them is fetched through AJAX as HTML. For example, there's a button in the modal: <button id="myBtn"> and ...

Issue encountered with Bing webmaster API when retrieving keyword statistics: an unknown error occurred resulting in an empty

My goal is to retrieve keyword statistics through the bing webmaster API using JSON GET requests. The required parameters for this operation are as follows: List<KeywordStats> GetKeywordStats( string q, string country, //optional s ...

Using AngularJS directives in Markdown

I am currently working on creating a custom HTML directive using AngularJS that will allow me to display Markdown content in the browser. My goal is to have a <markdown> element with a src attribute that will dynamically load and render the specified ...

Verify the visibility of the toggle, and eliminate the class if it is hidden

I have implemented two toggles in the code snippet below. I am trying to find a solution to determine if either search-open or nav-open are hidden, and if they are, then remove the no-scroll class from the body element. $(document).ready(function() { ...

Tips for choosing elements that are not next to each other in a JavaScript array

If I have an array and want to select non-consecutive elements, such as the second and fifth elements, is there a simple method to do this? For example: a = ["a","b","c","d","e"] a.select_elements([1,4]) // should yield ["b","e"] EDIT: After some reflec ...

Unable to utilize Bower due to a node.js malfunction

Currently facing an issue while attempting to utilize bower for installing all necessary components for my website project. Each time I make an attempt, the following error presents itself: TypeError: Object #<Object> has no method 'toLowerCase ...

Ways to extract information from JSON files

Currently, I am working on a script to extract viewer count and follower count data from Twitch. While I have successfully retrieved the viewer count information, I am encountering issues with extracting the follower count. The essential information can be ...

Error 403 occurs after submitting the form

Recently, I encountered a 403 error when attempting to submit the form on this page. Interestingly, when I directly accessed the new page by typing the URL into my browser, it loaded without any issues. The PHP code in the initial page looks like this: & ...

Is there a way to retrieve files stored on my hard drive within a webpage?

I have a large number of files stored on my hard drive, all following the same format, 2014.C1.012.012 - full name of the file. They each have unique numbers and names. I want to create a local webpage where I can organize these files into a table w ...

Executing an Angular 4 script using a scheduled CRON job

We are currently facing a challenge with our Angular-built APP for Android phones. The logic has become quite intricate and we have decided to transfer it to our server, where it can be executed as a CRON job every hour instead of within the Phone APP it ...

What are the steps for updating an NPM package that was installed from a Git repository?

I'm struggling to understand how to update a package that was installed from a git repository. Let's say I have a package located at git+ssh://<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d4b3bda094b3bda0b8b5b6fab1 ...