Transforming a JavaScript object into a different shape

I need help converting a list of team objects containing team names, reporters, and statuses for each day into date-based objects with all teams and their respective statuses for each date.

I attempted the following code snippet but did not achieve the desired outcome.

teams.map(team => ({
    day: team.statuses.reduce((acc, it) => it.day),
    teams: {
        teamName: team.teamName
    }
}))

[
   {
      "teamName":"abc",
      "reportedBy": "user1",
      "statuses":[
         {
            "day":"10/12",
            "status":"green"
         },
         {
            "day":"10/11",
            "status":"green"
         },
         {
            "day":"10/09",
            "status":"green"
         }
      ]
   },
    {
      "teamName":"xyz",
      "reportedBy": "user2",
      "statuses":[
         {
            "day":"10/12",
            "status":"red"
         },
         {
            "day":"10/11",
            "status":"red"
         },
         {
            "day":"10/09",
            "status":"red"
         }
      ]
   }

]

The expected output should be:

[
  {
    "day": "1012",
    "teams": [
      {
        "teamName": "abc",
        "reportedBy": "user1",
        "status": "green"
      },
      {
        "teamName": "xyz",
        "reportedBy": "user2",
        "status": "red"
      }
    ]
  },
  {
    "day": "1011",
    "teams": [
      {
        "teamName": "abc",
        "reportedBy": "user1",
        "status": "green"
      },
      {
        "teamName": "xyz",
        "reportedBy": "user2",
        "status": "red"
      }
    ]
  },
  {
    "day": "1009",
    "teams": [
      {
        "teamName": "abc",
        "reportedBy": "user1",
        "status": "green"
      },
      {
        "teamName": "xyz",
        "reportedBy": "user2",
        "status": "red"
      }
    ]
  }
]

Answer №1

It seems that creating an empty array and populating it as you go might be a more suitable approach instead of using the reduce method in this scenario:

let input = [
   {
      "teamName":"abc",
      "reportedBy": "user1",
      "statuses":[
         {
            "day":"10/12",
            "status":"green"
         },
         {
            "day":"10/11",
            "status":"green"
         },
         {
            "day":"10/09",
            "status":"green"
         }
      ]
   },
    {
      "teamName":"xyz",
      "reportedBy": "user2",
      "statuses":[
         {
            "day":"10/12",
            "status":"red"
         },
         {
            "day":"10/11",
            "status":"red"
         },
         {
            "day":"10/09",
            "status":"red"
         }
      ]
   }
];

let output = [];

input.forEach(team =>
{
  let name = team.teamName;
  let reporter = team.reporter
  team.statuses.forEach(status =>
  {
    let dayItem = output.find(item => item.day == status.day);
    if(dayItem == null)
    {
      let newItem = {day: status.day, teams:[{status: status.status, reportedBy: reporter, teamName: name}]};
      output.push(newItem);
    }
    else
    {
      dayItem.teams.push({status: status.status, reportedBy: reporter, teamName: name})
    }
  });
});

console.log(JSON.stringify(output));

Answer №2

Here is a snippet of code that I have experimented with:

  const dayMapped = {};
  const dailyStatuses = [];

  teams.forEach((team) => {
        team.statuses.forEach((status) => {
            status.day = status.day.replace(/\//g, '');
            if (!dayMapped[status.day]) {
                dayMapped[status.day] = {
                    day: status.day,
                    teams: []
                };
                dailyStatuses.push(dayMapped[status.day]);
            }
    
            dayMapped[status.day].teams.push({
                teamName: team.teamName,
                reportedBy: team.reportedBy,
                status: status.status   
            });
        });
    });

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

.class selector malfunctioning

I'm currently developing a card game system where players can select a card by clicking on it and then choose where to place it. However, I've encountered an issue where nothing happens when the player clicks on the target place. Here is the li ...

Encountered an issue while trying to add images and text simultaneously in asp.net

I am trying to modify my code by adding an image along with the text. Here is the updated code: $(".ChatSend").click(function () { strChatText = $('.ChatText', $(this).parent()).val(); var recievertext= $('.ausern ...

What is the technique for retrieving the field type with the Jackson ObjectMapper?

Is there a way to extract the Java type for a specific JSON path using Jackson's ObjectMapper object and a particular Class? For example, consider the following classes: class User { String fullName; Integer age; Boolean active; // . ...

Characteristics of JSON data containing quotation marks within the property values

Is it possible to include JavaScript functions in JSON like the example below? My JSON library is struggling to process this structure because of the quotations. How can I address this issue? I specifically need to store JavaScript functions within my JSON ...

Is there a way to make the React component automatically refresh upon clicking the search button?

Just starting out with React and JavaScript, I decided to experiment with accessing a public API. Here is the function I created: import { useState } from "react"; import CountrySWR from "./CountrySWR"; export default function SearchFo ...

The Google Books API has encountered an authentication error with status code 401

Trying to access public data using the Google Books API locally: An error occurred with the authentication credentials. It seems that an OAuth 2 access token, login cookie, or another valid authentication credential is missing. For more information, visit ...

Is HTML-escaping necessary when implementing regex checks?

As I develop a web application that takes user input through HTML inputs and forwards it to my tomcat server for processing, my current workflow is as follows: Client JS -> collect HTML input -> perform regex validation -> if successful -> se ...

Exploring the integration of d3 in an Express application - encountering an error: document is not recognized

I am facing a challenge in my expressjs application where I need to dynamically render vertices in a graph using d3. However, the code execution order seems to be causing issues for me. When attempting to use the d3.select function, I encounter the followi ...

Using Angular to send data to a WCF JSON endpoint

I've been trying to send a request to a WCF JSON service endpoint from Angular, but I haven't had any luck so far. The service has been tested through other methods and is functioning properly for the specified URL. When checking with Firebug, I ...

Seeking specific parameter in a JSON array using JavaScript: A guide

Currently, I am working on a project that involves retrieving Facebook news feed data using the graph API. Upon receiving the JSON object, I display it on the page. The "Likes" section is presented as an array of JSON objects like this: data.likes: { ...

Creating a canvas with multiple label introductions can be achieved by following these

I am looking to group labels and sublabels on the x-axis of a canvas component. Currently, I only have sublabels like: RTI_0, RTI_1... I would like to add labels to these sublabels like: RTI = {RTI_0,RTI_1,RTI_2] BB = {BB_0, BB_1,BB_2,BB_3] <div cla ...

Extracting POST information through PHP's AJAX Request

I am facing an issue where I keep receiving null values when using the following code: Here is my Ajax request: formData = { u: "3959eeadb32e02b85a792e21c", id: "6d7613df26" }; $.ajax({ ...

Toggle the selection of a div by clicking a button in AngularJS with a toggle function

I have several div elements on a webpage. Each div contains a button! When the button is clicked for the first time: The border color of the div will change to blue (indicating the div is now selected). The "ok" button will be hidden (leaving only t ...

Can you provide insight on the recommended methodology for aggregating JSON data effectively?

Imagine having a dataset structured like this: let sampleData = [ {"YEAR": "2009", "MONTH": "1", "CUSTOMER": "Customer1", "REVENUE": "1938.49488391425"}, {"YEAR": "2009", "MONTH": "1", "CUSTOMER": "Customer2", "REVENUE": "75.9142774343491"}, {"YEAR": "200 ...

Having trouble with Jquery Ajax call in IE8?

I have a dynamic data loading from the database, with each row containing links that perform various actions. Most of them work perfectly fine, but I've noticed an issue with the last one I added – it doesn't seem to be functioning properly on ...

The onblur function is not being triggered

Recently, I encountered an issue while trying to invoke a JavaScript function onblur of a field. The main problems I faced were: 1) The popup inside the function call was triggered automatically during page load. 2) When attempting to access the functio ...

Transforming Java Properties Into Nested Map to Obtain JSON Format

For a fun project and internal tool development, I am working on converting a Java properties file to a JSON hierarchy. foo.bar=15 foo.lots.dir=/tmp/test foo.baz.host=localhost foo.baz.port=333 I have successfully converted it to a Scala map, here' ...

Mapping YAML file to a Java Map without using a custom deserializer

I have a YAML file that I want to load into a Map instance without having to define a custom deserializer. Is there a way to achieve this using annotations or any other method? Below is an example of the YAML file: - site: First Site url: some_url us ...

It is advisable to keep extra information in req.params for better practice

As I work on developing a RESTful API for my web application, I have discovered a helpful practice. When creating various routes and implementing the logic for each one, I found it beneficial to store any additional data needed in the req object under the ...

Does anyone have any sample code on processing JSON data from a URL using Modified JavaScript Value in Java?

Could anyone provide some examples on how to handle returned Json data using Modified JavaScript Value? Here is the specific data I require from the json url: { "result": { "data": [ { "name": "page1", "period": "dia", "values": [ { "value": 4, "end_time" ...