Sort, Transform, and Condense

In my code snippet, I have a loop that iterates over an array and manipulates the data:

          $scope.listDeColaboradoresObject.forEach(item => {
            item.listNmAssunto = $scope.relatorioTotalMensagensRespondidasColab
              .filter(x => x.nmUsuario == item.nmUsuario)
              .map(x => x.nmAssunto);
            item.listNmAssunto = $scope.removeDuplicates(item.listNmAssunto);

            item.listDtResposta = $scope.relatorioTotalMensagensRespondidasColab
              .filter(x => x.nmUsuario == item.nmUsuario)
              .map(x => x.dtResposta);

          });

The initial data in the array looks like this:

0: {deTipoAtendimento: "012", nmAssunto: "Cartão extraviado", nmUsuario: "15", dtResposta: "2018", total: 1}
1: {deTipoAtendimento: "012", nmAssunto: "Assunto Novo 012", nmUsuario: "Admin", dtResposta: "2018", total: 2}
2: {deTipoAtendimento: "012", nmAssunto: "Assunto Novo 012", nmUsuario: "Administrador", dtResposta: "2018", total: 1}
3: {deTipoAtendimento: "012", nmAssunto: "Assunto Novo 012", nmUsuario: "Administrador IMB", dtResposta: "2018", total: 3}
4: {deTipoAtendimento: "012", nmAssunto: "Assunto Teste GREAt", nmUsuario: "Administrador IMB", dtResposta: "2018", total: 2}
5: {deTipoAtendimento: "012", nmAssunto: "Thais 23042018", nmUsuario: "Administrador IMB", dtResposta: "2018", total: 2}
6: {deTipoAtendimento: "012", nmAssunto: "teste Alterado2", nmUsuario: "Administrador IMB", dtResposta: "2018", total: 1}

After running the code, the resulting array is:

0: {nmUsuario: "15", listNmAssunto: Array(1), listDtResposta: Array(1), $$hashKey: "object:2975"}
1: {nmUsuario: "Admin", listNmAssunto: Array(1), listDtResposta: Array(1), $$hashKey: "object:2976"}
2: {nmUsuario: "Administrador", listNmAssunto: Array(1), listDtResposta: Array(1), $$hashKey: "object:2977"}
3: {nmUsuario: "Administrador IMB", listNmAssunto: Array(4), listDtResposta: Array(4), $$hashKey: "object:2978"}

My query is about how to combine both the subject name (nmSubject) and date of response (dtResponse) into a single array during the mapping process.

Answer №1

Why is it not recommended to map into a single object like this?

          $scope.listCollaboratorsObject.forEach(entry => {
        entry.subjectList = $scope.totalMessagesRespondedCollab
          .filter(response => response.userName == entry.userName)
          .map(response => {a:response.subject,b: response.date});
        entry.uniqueSubjects = $scope.removeDuplicates(entry.subjectList);

      });

Answer №2

The code provided will update the existing array, but it's unclear how it generates the posted output. Based on the desired output, it seems like you want to group data by the nmUsuario and create an array of objects with two array properties. This can be achieved using reduce, destructuring, and Object.values.

const input = [{deTipoAtendimento:"012",nmAssunto:"Cartão extraviado",nmUsuario:"15",dtResposta:"2018",total:1},{deTipoAtendimento:"012",nmAssunto:"Assunto Novo 012",nmUsuario:"Admin",dtResposta:"2018",total:2},{deTipoAtendimento:"012",nmAssunto:"Assunto Novo 012",nmUsuario:"Administrador",dtResposta:"2018",total:1},{deTipoAtendimento:"012",nmAssunto:"Assunto Novo 012",nmUsuario:"Administrador IMB",dtResposta:"2018",total:3},{deTipoAtendimento:"012",nmAssunto:"Assunto Teste GREAt",nmUsuario:"Administrador IMB",dtResposta:"2018",total:2},{deTipoAtendimento:"012",nmAssunto:"Thais 23042018",nmUsuario:"Administrador IMB",dtResposta:"2018",total:2},{deTipoAtendimento:"012",nmAssunto:"teste Alterado2",nmUsuario:"Administrador IMB",dtResposta:"2018",total:1}]

const merged = input.reduce((r,{ nmUsuario, nmAssunto, dtResposta }) => {
  r[nmUsuario] = r[nmUsuario] || {nmUsuario, listNmAssunto: [], listDtResposta:[]};
  r[nmUsuario].listNmAssunto.push(nmAssunto);
  r[nmUsuario].listDtResposta.push(dtResposta);
  return r;
}{}

const output = Object.values(merged);
console.log(output)

Answer №3

Based on your feedback, it seems that you are interested in grouping your list by nmUsuario, while creating a unified array of objects containing the relevant information from nmAssunto and dtResposta. This can be accomplished using the reduce() function. Essentially, you initialize an object with an empty array for each unique nmAssunto, then add a new object to the correct array during each iteration. Finally, utilize Object.values() to convert the data into the desired output array.

const data = [
  {deTipoAtendimento:"012",nmAssunto:"Cartão extraviado",nmUsuario:"15",dtResposta:"2018",total:1},
  {deTipoAtendimento:"012",nmAssunto:"Assunto Novo 012",nmUsuario:"Admin",dtResposta:"2018",total:2},
  {deTipoAtendimento:"012",nmAssunto:"Assunto Novo 012",nmUsuario:"Administrador",dtResposta:"2018",total:1},{deTipoAtendimento:"012",nmAssunto:"Assunto Novo 012",nmUsuario:"Administrador IMB",dtResposta:"2018",total:3},
  {deTipoAtendimento:"012",nmAssunto:"Assunto Teste GREAt",nmUsuario:"Administrador IMB",dtResposta:"2018",total:2},
  {deTipoAtendimento:"012",nmAssunto:"Thais 23042018",nmUsuario:"Administrador IMB",dtResposta:"2018",total:2},
  {deTipoAtendimento:"012",nmAssunto:"teste Alterado2",nmUsuario:"Administrador IMB",dtResposta:"2018",total:1}
]

const groups = data.reduce((r, { nmUsuario, nmAssunto, dtResposta }) => {
  r[nmUsuario] = r[nmUsuario] || {
    nmUsuario,
    listAssunto: []
  }
  r[nmUsuario].listAssunto.push({
    a: nmAssunto,
    b: dtResposta
  })
  return r
}, {})
 
console.log(Object.values(groups))

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

What is the best way to add a new div below a specific div without disrupting the existing layout of other elements on the page?

Is there a way to create a new div that appears below a specific div on a webpage, but is displayed above all other elements without affecting their positioning? Here is an example: --------------------------------------------- | | ...

Creating functionality in Ionic to allow for the dynamic addition of buttons to the navigation bar

I have a navigation bar and I would like to include a save button on it for just one screen. After going through various blogs, I found that the general advice is to declare buttons in the view rather than accessing them in a controller. But still, isn&apo ...

Display header right button based on a condition in React Native using React Navigation

I am looking to conditionally display the Entypo new-message icon in the top right corner of the header based on a boolean variable (if true, then show the icon in the header). Here is a snippet of code where this functionality can be replicated. Thank y ...

Establish a many-to-many relationship in Prisma where one of the fields is sourced from a separate table

I'm currently working with a Prisma schema that includes products, orders, and a many-to-many relationship between them. My goal is to store the product price in the relation table so that I can capture the price of the product at the time of sale, re ...

Creating a drawImg function on the HTML/JavaScript canvas

Attempting to duplicate a specified section of an image onto a canvas below, but finding that the mirrored section is resizing unexpectedly. For example, if given a map image and trying to replicate a building from it exactly below, why does the mirrored s ...

What is the best method for setting up message scheduling for a Microsoft Teams bot based on different time

I am trying to figure out how to send messages to users from my bot at specific time intervals. Currently, I'm using agenda for scheduling messages, but I've run into an issue with the timezone discrepancy - agenda is 5:30 hours behind my timezon ...

Storing Array Data in Angular $scope (Javascript)

I am currently altering the Altair Material Design Template and incorporating an Angular JS controller. After successfully calling an API and creating variables in a for loop, I intend to write them to $scope.dragulaItems. While this process seems to work ...

Transform the file format from .casa-model to .obj

Looking for a way to convert a file with the extension .casa-model to .obj format. Is there any solution available? Find the model here. ...

Utilizing the Power of AJAX in Combination with an Event Loop

I have a function that is supposed to make AJAX requests with an event loop while taking 9 inputs at the top and querying them from a database. Currently, it only logs to the console but will eventually perform more actions. However, I am encountering an ...

Exploring the power of Vuejs3 with Internationalization and the Composition API

Currently, I am working on a frontend interface in VueJS and integrating i18n with Vuejs 3. While the normal implementation of i18n works fine, I encountered issues when trying to use it with the composition API. In my main.js file, I have set up i18n as ...

Failure in SystemJS during ahead-of-time compilation due to missing NgZone provider

Previously, I have successfully used Angular's ahead-of-time compilation. However, after adding routing and lazy loading to my app, I am facing difficulties in making it work again. Upon updating my code to the latest 2.0 release, it functions well w ...

The element div is not permitted as a child of the element h5 in this particular scenario

My code snippet is as follows: $compile .= "<h5 data-count='".$acctemmpi. "' class='shortcode_accordion_item_title expanded_". $expanded_state . "'>" . $title . "<div class='ico'&g ...

Is there a way to ensure that GIFs in jQuery Mobile always start from the beginning?

My cross-platform mobile app built with jQuery Mobile is a small quiz application. After each correct or wrong answer, I display a 3-second GIF. Currently, I have set up the code to show the GIF for 3 seconds before moving on to the next page: else if ($. ...

I'm curious why my phone number is being treated as an object when it's passed in as a prop

I am facing an issue with my FooterScroll component while using it on the TvIndex main page. This is the FooterScroll Component const FooterScroll = (Id: number) => { const { event } = useEvent(Id); console.log('Id', Id); return ( ...

Which of the two async functions will be executed first?

const [counter, setCounter] = useState(0) Consider the scenario where we have two asynchronous functions, func1 and func2, both of which are responsible for updating the counter state. It is specified that func1 is supposed to execute before func2. async ...

What is the reason for the automatic loading of coffee files in app/assets/javascripts across all files?

I have a question about organizing my Javascript files in my app. I have multiple files in the app/assets/javascripts folder, and for testing, I have written some code in a file named test.coffee: $ -> $(document).ready -> alert("Hey"); When ...

AngularJS - How to loop through a div to display all items

I am working with AngularJS to create a repeatable shopping cart items feature. Below is a sample JSON data structure: [{"src": "img/T1.jpg", "itemname": "solid green cotton tshirt", "style": "MS13KT1906", "colour": "Blue", "size": "s", "qty": "1", "price ...

Prisma data is not being returned as an array in getServerProps with React Next.js

My Journey with Next.js and Prisma Having recently grasped the concept of getServerProps, I embarked on a project that involved retrieving data from a PostgreSQL database using Prisma. However, despite diligently following the syntax rules outlined in the ...

Utilizing JSON in a d3.js application within a Rails environment

I have been exploring the gem gon in order to generate JSON data from my Rails database. I have successfully managed to display this data in an alert, but now I am looking to visualize it using d3.js. Within my database named "users" with columns (name:st ...

Utilizing AJAX to add information to jQuery data tables without taking advantage of their pagination and advanced features

The jQuery datatables plugin is a useful tool for adding filters, pagination, and search functionality to web applications. I have personally integrated it with my Laravel project to organize and display data effectively. Recently, I decided to enhance th ...