Organize array of objects based on the "dataPrin" field

I've been attempting to group this array by the "dataPrin" field for some time now, but without success.

It's worth noting that there are two instances of the "dataPrin" field displaying the same date.

My goal is to organize this array in a way that if there are duplicate "dataPrin" fields with the same date, they should be grouped into one entry, just like the example provided below.

Is it feasible to achieve this using 'reduce'? I would greatly appreciate any assistance from the community.

Here is the current array:

[{
    "dataPrin": "2021-05-31T16:10:28-03:00",
    "selectAll": false,
    "lancamentos": [{
            "cod_transacao": 1510,
            "num_cpf_cnpj": "11.414.555/0001-04",
            "dt_lancamamento": "2021-05-31T16:29:28-03:00",
        }]
},
{
    "dataPrin": "2021-05-29T16:30:28-03:00",
    "selectAll": false,
    "lancamentos": [{
            "cod_transacao": 1511,
            "num_cpf_cnpj": "11.414.555/0001-04",
            "dt_lancamamento": "2021-05-31T16:29:28-03:00",
        }]
},
{
    "dataPrin": "2021-05-29T16:15:28-03:00",
    "selectAll": false,
    "lancamentos": [{
            "cod_transacao": 1512,
            "num_cpf_cnpj": "11.414.555/0001-04",
            "dt_lancamamento": "2021-05-31T16:29:28-03:00",
        }]
}]

Desired output:

[{
    "dataPrin": "2021-05-31T16:10:28-03:00",
    "selectAll": false,
    "lancamentos": [{
            "cod_transacao": 1510,
            "num_cpf_cnpj": "11.414.555/0001-04",
            "dt_lancamamento": "2021-05-31T16:29:28-03:00",
        }]
},
{
    "dataPrin": "2021-05-29T16:30:28-03:00",
    "selectAll": false,
    "lancamentos": [{
            "cod_transacao": 1511,
            "num_cpf_cnpj": "11.414.555/0001-04",
            "dt_lancamamento": "2021-05-31T16:29:28-03:00",
        },
        {
            "cod_transacao": 1512,
            "num_cpf_cnpj": "11.414.555/0001-04",
            "dt_lancamamento": "2021-05-31T16:29:28-03:00",
        }]
}]

Answer №1

Here is the code snippet for you:

var details = [{
              "primaryData": "2021-05-31T16:10:28-03:00",
              "selectOption": false,
              "transactions": [{
                      "transaction_code": 1510,
                      "tax_id_number": "11.414.555/0001-04",
                      "transaction_date": "2021-05-31T16:29:28-03:00",
                  }]
          },
          {
              "primaryData": "2021-05-29T16:30:28-03:00",
              "selectOption": false,
              "transactions": [{
                      "transaction_code": 1511,
                      "tax_id_number": "11.414.555/0001-04",
                      "transaction_date": "2021-05-31T16:29:28-03:00",
                  }]
          },
          {
              "primaryData": "2021-05-29T16:15:28-03:00",
              "selectOption": false,
              "transactions": [{
                      "transaction_code": 1512,
                      "tax_id_number": "11.414.555/0001-04",
                      "transaction_date": "2021-05-31T16:29:28-03:00",
                  }]
          }]

const temporary = details.reduce((result, item)=>{
            const dateValue = item.primaryData.split('T')[0];

            if(dateValue in result){
              result[dateValue].transactions.push(...item.transactions)
            }else{
              result[dateValue] = item;
            }
            return result
          },{});
const desiredOutput = Object.keys(temporary).map(c=>temporary[c])

Answer №2

This code snippet is ideal for utilizing the reduce() method.

const data = [{
    "dataPrin": "2021-05-31T16:10:28-03:00",
    "selectAll": false,
    "lancamentos": [{
      "cod_transacao": 1510,
      "num_cpf_cnpj": "11.414.555/0001-04",
      "dt_lancamamento": "2021-05-31T16:29:28-03:00",
    }]
  },
  {
    "dataPrin": "2021-05-29T16:30:28-03:00",
    "selectAll": false,
    "lancamentos": [{
      "cod_transacao": 1511,
      "num_cpf_cnpj": "11.414.555/0001-04",
      "dt_lancamamento": "2021-05-31T16:29:28-03:00",
    }]
  },
  {
    "dataPrin": "2021-05-29T16:15:28-03:00",
    "selectAll": false,
    "lancamentos": [{
      "cod_transacao": 1512,
      "num_cpf_cnpj": "11.414.555/0001-04",
      "dt_lancamamento": "2021-05-31T16:29:28-03:00",
    }]
  }
]

let ndata = data.reduce((accumulator, currentValue) => {
  let iden = currentValue.dataPrin.split("T")[0];
  if (accumulator.hasOwnProperty(iden)) currentValue.lancamentos.forEach(l => accumulator[iden].lancamentos.push(l));
  else accumulator[iden] = currentValue;
  return accumulator
}, {})

console.log(ndata);

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

Is there a way to determine if an array contains multiple occurrences of unidentified strings?

Is there a way in JavaScript to determine if an array contains two or more identical values? For instance; ['one','two','three'] -> false, because no items in the array are repeated. ['one','one',&apo ...

"Each time I use jQuery.getJSON with JSONP, the same data is being returned regardless of the

Using jQuery.getJSON(), I am hitting the same web service three times consecutively with different parameters to draw charts with the received data. The issue lies in the fact that, while obtaining the data in my callback function, it is not consistently a ...

Can you explain how to utilize a function on a client component in Next.js?

I'm a bit lost on how client components function. I am working on an image uploader project where I need to extract the userId from supabase, utilize the supabase server function, and then upload the image to supabase storage with the "userId/filename ...

Validation in AngularJS is limited to only accepting integers with the use of the

Can you help me with validating positive integer numbers using the ng-pattern attribute? Currently, I have this pattern: ^[0-9]{1,7}(\.[0-9]+)?$/, but it also allows decimal values. I want to restrict it to only accept whole numbers. ...

simulate express-jwt middleware functions for secure routes

I am currently facing an issue with my code snippet, which looks like this: import app from '../src/app'; beforeAll(() => jest.mock('../src/middleware/auth', () => (req: Request, res: Response, next: NextFunction) => { ...

Shifting image from center to corner as you scroll

Hello there, I'm new to this so please bear with me for any obvious mistakes, thank you :) My goal is to have an image move from the center of the screen to the corner of the screen as you start scrolling. I've made some progress on this, but I& ...

Locate components within the Data object of jQuery's .get() method

It's proving to be a bit more challenging than I initially thought :) $.get('/page.html', function(data) { //extract only the elements with the "contents" class }); I'm struggling to figure out the best way to achieve that. ...

I have a dynamic blog site that is generated on the fly using Ajax, making the content unsearchable

I have a blog website that is created dynamically using Ajax (XMLHttpRequest) and the HTML History API. One issue I am facing is that my content is not searchable by search engines like Googlebot. I know that Google is now able to analyze such sites, but w ...

Using NodeJS to assign key-value pairs to a JSON object

I am currently working with a NodeJS script that receives data in the form of "key, value" pairs and I need to transform this data into a JSON object. The data is obtained using SNMP where the key corresponds to the OID. My goal is to efficiently map thes ...

The malfunctioning of my Ajax functionality is causing issues

Today, I delved into the world of Ajax. I took the time to practice and follow step-by-step instructions on how to use AJAX, but unfortunately, I encountered an issue. I couldn't pinpoint the problem as there were no warnings displayed in the console. ...

Issue with updating state in child component preventing addition to state

Recently, I made the switch to TypeScript in my NextJS project using Create T3 App. One of the components in my app involves updating the state after a Prisma mutation is performed. I attempted to pass the setItems (which was initialized with useState) to ...

Is there a way to properly test a Vue component that is watching a ref prop?

I am currently testing a Vue component that should display a success icon for 3 seconds when the loading state changes from true to false. I have encountered challenges while trying to write a component test using Vue Testing Library or Vue test utils du ...

The function of window.location is a mixed bag of success and failure

I am encountering an issue with a JavaScript function that is supposed to navigate to the next page when clicking a button. The function works correctly for step 1, but it fails for step 2. Upon executing the function using nextstep = 'form', _b ...

How can I add an image to a canvas using a button?

Having trouble with my studies and looking to create a custom shirt website. Posted below is the beginner code I have: If anyone knows how to upload an image onto a shirt canvas using a button, as well as change the shirt color with another button, please ...

How do I select the first element with class "cell" in D3, similar to jQuery's $(".cell:first")?

I have attempted this: d3.select(".cell:first") d3.selectAll(".cell").filter(":first") d3.selectAll(".cell").select(":first") but unfortunately, none of these methods are effective. ...

ng-repeat refreshes after compilation

I have a collection of upcoming events retrieved through a JSON request to my server. These events are displayed using ng-repeat in my application. I am looking to add functionality where users can like or unlike an event by clicking on a button. <a ng ...

Arranging images next to each other using CSS and HTML

I've been trying to arrange four images side by side, with two on the top row and two on the bottom. I want to ensure they stay consistent across all browser sizes except for mobile. Here is what I have attempted so far: #imageone{ position: absol ...

``Maneuvering through dynamically generated cells with multiple colsp

I'm currently working on creating a table using data from Vue.js. Depending on the value of a specific column, I want to split the cells into either 2 or 3 columns. Take a look at this image: The cell in row 01 and col 01 should be split into 3 vert ...

Implementing a feature in AngularJS to dynamically disable buttons based on the current date and time

My store list includes day-wise shop opening and closing times. I need to compare the current day and time with each store's schedule (day, open time, and close time). If the current day and time match a store's opening time, the order button sho ...

What is the best way to arrange a MongoDB collection by proximity to geographic coordinates?

Can someone help me with sorting the list of places based on the nearest geo coordinates in this Mongo call? Venues.find({'location.coordinates': { $near : { $geometry : { type : "Point" , coordinates: params ...