Generating a collection of items using a pre-existing array of items

Struggling to create an array of objects based on another array of objects. I attempted to use flatMap and then reduce, but encountered an issue when I tried to collect multiple statuses in one object. Below is what I have attempted and the desired result I aim to achieve:

My Initial Data:

const data = [
        {
            "timestamp": "2021-08-31T15:29:18Z",
            "result": [
                {
                    "label": "Not Covered",
                    "value": 132
                }
            ]
        },
        {
            "timestamp": "2021-09-30T15:29:18Z",
            "result": [
                {
                    "label": "Not Covered",
                    "value": 135
                }
            ]
        },
        {
            "timestamp": "2021-10-31T16:29:18Z",
            "result": [
                {
                    "label": "Not Covered",
                    "value": 135
                }
            ]
        }
    ]
    

Desired Output:

[
        {
            "Not Covered": 132,
            "Active": 0,
            "Expiring Soon": 0,
            "timestamp": "2021-08-31T15:29:18Z"
        },
        {
            "Not Covered": 135,
            "Active": 0,
            "Expiring Soon": 0,
            "timestamp": "2021-09-30T15:29:18Z"
        },
        {
            "Not Covered": 135,
            "Active": 0,
            "Expiring Soon": 0,
            "timestamp": "2021-10-31T16:29:18Z"
        }
    ]
    

Current Approach:


    let flattenedResult = data.flatMap(({result, ...r}) => result.map(o => ({ ...o, ...r})));
    
    const chartData = flattenedResult.reduce((acc, item) => {
        const {timestamp, value, label} = item;
    
        acc.push({timestamp, "Not Covered": "Not Covered" === label ? value : 0, "Active": "Active" === label ? value : 0, "Expiring Soon": "Expiring Soon" === label ? value : 0});
        return acc;
    }, []); 
    

Current Output:

[
        {
            "timestamp": "2021-08-31T15:29:18Z",
            "Not Covered": 132,
            "Active": 0,
            "Expiring Soon": 0
        },
        {
            "timestamp": "2021-09-30T15:29:18Z",
            "Not Covered": 135,
            "Active": 0,
            "Expiring Soon": 0
        },
        {
            "timestamp": "2021-10-31T16:29:18Z",
            "Not Covered": 135,
            "Active": 0,
            "Expiring Soon": 0
        }
    ]
    

Answer №1

The process for obtaining the values "Active" and "Expiring soon" has not been fully elaborated upon, but it is assumed that implementing something similar might be beneficial

const data = [
    {
        "timestamp": "2021-08-31T15:29:18Z",
        "result": [
            {
                "label": "Expiring Soon",
                "value": 57
            },
            {
                "label": "Not Covered",
                "value": 132
            },
            {
                "label": "Active",
                "value": 42
            }
        ]
    },
    {
        "timestamp": "2021-09-30T15:29:18Z",
        "result": [
            {
                "label": "Not Covered",
                "value": 135
            }
        ]
    },
    {
        "timestamp": "2021-10-31T16:29:18Z",
        "result": [
            {
                "label": "Not Covered",
                "value": 135
            },
            {
                "label": "Active",
                "value": 42
            }
        ]
    }
];

console.log(data.reduce((acc, {timestamp, result}) => {
    const datum = result.reduce((acc, {label, value}) => {
        acc[label] = value;
        return acc;
    }, {
        timestamp,
        'Not Covered': 0,
        Active: 0,
        'Expiring Soon': 0
    });
    return acc.concat(datum);
}, []));

Answer №2

Would you consider implementing a solution like this? You could customize the "Active" and "ExpiringSoon" based on your specific business requirements.

const array = data.map(item => {
  const results = {}
  item.result.forEach(({ label, value }) => results[label] = value )
  return {
    Active: 0,
    ExpiringSoon: 0,
    timestamp: item.timestamp,
    ...results
  }
})

Here is the expected result

[
  {
    Active: 0,
    ExpiringSoon: 0,
    timestamp: '2021-08-31T15:29:18Z',
    'Not Covered': 132
  },
  {
    Active: 0,
    ExpiringSoon: 0,
    timestamp: '2021-09-30T15:29:18Z',
    'Not Covered': 135
  },
  {
    Active: 0,
    ExpiringSoon: 0,
    timestamp: '2021-10-31T16:29:18Z',
    'Not Covered': 135
  }
]

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

Incorporate a Three.js viewer within a WPF application

I am currently exploring the use of Three.js to develop a versatile 3D renderer that can run seamlessly on various platforms through integration with a "WebView" or "WebBrowser" component within native applications. I have successfully implemented this sol ...

Transferring a Query between Domains with the Help of JavaScript

It is necessary to develop a function that generates a query based on the user's input of "Test" in an INPUT on Site A (SiteA.com) and then redirects to Site B within the same window, passing along the query (SiteB.com/search.aspx?k=test). Code snipp ...

Is it possible to verify if each input is unique using the parsley validator?

As a novice, I am struggling with a task where I have 6 School Children IDs. The teacher needs to input these IDs, and while it's not vital for him to enter all of them, he must input at least one. Furthermore, if he decides to input more than one ID, ...

Implementing the 'bootstrap tour' feature in a Ruby on Rails application

I have integrated bootstrap-tour.min.css and bootstrap-tour.min.js into my project. <script type="text/javascript" src='bootstrap-tour.min.js'></script> <link rel="stylesheet" type="text/css" href="bootstrap-tour.min.css"> Her ...

Executing server-side method with jQuery in .Net 1.1

Currently, I am utilizing .net1.1 and attempting to invoke a server-side method using jQuery upon clicking the browser's Close button. However, my code does not seem to be functioning correctly. I have provided my code below for reference. Can anyone ...

What are the steps to start up a NodeJS API using an Angular app.js file?

Currently, I am following various online tutorials to develop a web application using the MEAN stack and utilizing a RESTful API. I have encountered some challenges in integrating both the API server and Angular routes. In my project, I have a server.js f ...

Tips for troubleshooting a timeout issue in electron-html-to with node.js

Encountering a timeout issue while attempting to convert an html file to pdf using electron. The js app is being run through node. `{ Error: Worker Timeout, the worker process does not respond after 10000 ms at Timeout._onTimeout (C:\Users\Owner ...

My applications are not firing the deviceready event as expected

Struggling to incorporate a cordova plugin into my vue.js project using vue-cordova. Specifically, I am attempting to utilize the open-native-settings plugin to access device settings on iOS or Android. While it works seamlessly in the demo app provided b ...

From time to time, I may post files of substantial size

When moving to the next step in the form, I have implemented checks to prevent photos over 10mb and disallow .heic files from being uploaded. Most of the time it works as expected, but occasionally files slip through. If anyone has suggestions for a more ...

Tips for sharing content within an iframe

Despite my efforts to find a solution, I have been unable to come across one that aligns with my specific situation. I currently have a form for inputting person data. Within this form, there is an iframe containing another form for adding relatives' ...

Building a Many-to-Many Relationship in Node.js Using Sequelize.js

As I utilize the sequelize node.js module to structure schema in Postgres SQL, I have defined two schemas for Project and my users. Project Schema module.exports = function(sequelize, DataTypes) { var project = sequelize.define('project', { ...

Applying CSS styles to a page depending on certain conditions

Currently, I have a page in SharePoint that can function as a pop-up. I am using JavaScript to identify whether it is a pop-up by checking if window.location.search.match("[?&]IsDlg=1"). However, I am struggling to figure out how to insert CSS based on ...

Guide on invoking a Python function using vanilla JavaScript within a Django application

I'm currently developing a Django application and I'm attempting to invoke a Python function in views.py upon clicking a button. I'm aiming to achieve this using vanilla JavaScript, as my knowledge of JavaScript is limited and I prefer to ke ...

A simple way to deactivate a React component (or the onClick event itself) using the onClick event

I have come across similar inquiries, but unfortunately, none of the solutions provided seem to work in my particular scenario. I am hopeful that someone can shed some light on what might be causing the issue. In my ReactApp, there are 3 card components t ...

There was an error with the response code of 500 on the development server for react-native

An issue has been encountered on the node.js window: error: bundling failed: Error: Unable to resolve module react-native-gesture-handler from node_modules\@react-navigation\native\src\Scrollables.js: react-native-gesture-handler could ...

What is the best way to prevent Firefox from storing the data of a textarea in the local environment?

I have been developing a website locally, and I have noticed that there are numerous <textarea> elements present on the site. One issue I am facing is that whenever I reload the site, the content within the <textarea> remains the same. This pe ...

Exploring how arrays are managed in Excel with the SUMPRODUCT() function

There are three arrays labeled A, B, and C where A - B = C. In excel, these arrays are organized in columns as follows: A, B, C, A, B, C, A, B, C... D, E The objective is to calculate the sum of all values in C that are greater than 0 (D) and all values ...

Inquiring about utilizing res.render and invoking functions within an EJS template

Exploring node, I created a practice function in a separate file and imported it to my server.js. With express as my framework, passing the function in the res.render object with a parameter works seamlessly. app.get('/projects', (req, res) => ...

Using callbacks in Node.js to pass variables

I'm relatively new to working with node and I'm attempting to develop a function that retrieves server information. However, I've encountered an issue. I've set up a config object (which will eventually be dynamically updated by certain ...

Error: Swagger-codegen encountered an issue where 'Object' arguments were disregarded

I've encountered a strange error that I can't seem to troubleshoot through online searches. My current project involves converting swagger files to typescript using a script. The error message simply states what's in the title, and unfortuna ...