Changing an array of object arrays into a consolidated array in JavaScript

I am working with an array of objects that contain nested arrays.

 const arr =  [
    {
        JUNE: [
            {
                "iD": "67854",
                "event": " closed",
                "title": "test",
                "startDate": "2024-06-20",
                "endDate": "2024-07-25"
            }
        ]
    },
    {
        MAY: [
            {
                "ID": "908765",
                "event": "closed",
                "title": "test",
                "startDate": "2024-05-21",
                "endDate": "2024-06-27"
            },
            {
                ID: "12345",
                event: "open",
                title: "test123",
                startDate: "2024-05-21",
                endDate: "2024-06-27"
            }
        ]
    }
]

I require the following output:

   [
    {
        ID: "67854",
        event: "closed",
        title: "test",
        startDate: "2024-06-20",
        endDate: "2024-07-25"
    },
    {
        ID: "908765",
        event: "closed",
        title: "test",
        startDate: "2024-05-21",
        endDate: "2024-06-27"
    },
    {
        ID: "12345",
        event: "open",
        title: "test123",
        startDate: "2024-05-21",
        endDate: "2024-06-27"
    }

]

Answer №1

Use <code>arr.flatMap(Object.values).flat()
to efficiently achieve the desired outcome.

const arr = [{JUNE: [{"iD": "67854", "event": " closed", "title": "test", "startDate": "2024-06-20", "endDate": "2024-07-25" } ] }, {MAY: [{"ID": "908765", "event": "closed", "title": "test", "startDate": "2024-05-21", "endDate": "2024-06-27" }, {ID: "12345", event: "open", title: "test123", startDate: "2024-05-21", endDate: "2024-06-27" } ] } ];

const result = arr.flatMap(Object.values).flat();

console.log(result)

Answer №2

If you're not interested in the months and just want to flatten it out, use flatMap and flat():

const arr =  [{JUNE: [{"iD": "67854", "event": " closed", "title": "test", "startDate": "2024-06-20", "endDate": "2024-07-25" } ] }, {MAY: [{"ID": "908765", "event": "closed", "title": "test", "startDate": "2024-05-21", "endDate": "2024-06-27" }, {ID: "12345", event: "open", title: "test123", startDate: "2024-05-21", endDate: "2024-06-27" } ] } ];

const res = arr.flatMap(c => Object.values(c).flat());

console.log(res)


If you want to include the month, then reduce the array and flatMap each Object.keys with a deeper map for all the events.

const arr =  [{JUNE: [{"iD": "67854", "event": " closed", "title": "test", "startDate": "2024-06-20", "endDate": "2024-07-25" } ] }, {MAY: [{"ID": "908765", "event": "closed", "title": "test", "startDate": "2024-05-21", "endDate": "2024-06-27" }, {ID: "12345", event: "open", title: "test123", startDate: "2024-05-21", endDate: "2024-06-27" } ] } ];

const res = arr.reduce((p, c) => ([ ...p, 
    ...(Object.keys(c)
        .flatMap(month => c[month]
          .map(o => ({ ...o, month })) )) 
        ])
, []);

console.log(res)

Or as a one-liner:

const res = arr.reduce((p, c) => ([ ...p,...(Object.keys(c).flatMap(month => c[month].map(o => ({ ...o, month })))])], []);

Answer №3

To tackle this problem (particularly challenging if you are not well-versed in the topic), one approach is to leverage reduce and concat in the following way:

const arr = [{JUNE:[{iD:"67854",event:" closed",title:"test",startDate:"2024-06-20",endDate:"2024-07-25"}]},{MAY:[{ID:"908765",event:"closed",title:"test",startDate:"2024-05-21",endDate:"2024-06-27"},{ID:"12345",event:"open",title:"test123",startDate:"2024-05-21",endDate:"2024-06-27"}]}];

const result = arr.reduce((acc, eventsByMonth) => acc.concat(
  ...Object.entries(eventsByMonth).reduce((acc, [month, events]) => acc.concat(
    ...events.map(event => ({ month, ...event }))
  ), [])
), []);

console.log(result);

reduce enables iteration over an array and data aggregation into an accumulator. Here, the accumulator serves as the resulting array.

Answer №4

You have the option to simplify your code by using a reduce method to flatten the array:

const arr = [
    {
        JUNE: [
            {
                "iD": "67854",
                "event": " closed",
                "title": "test",
                "startDate": "2024-06-20",
                "endDate": "2024-07-25"
            }
        ]
    },
    {
        MAY: [
            {
                "ID": "908765",
                "event": "closed",
                "title": "test",
                "startDate": "2024-05-21",
                "endDate": "2024-06-27"
            },
            {
                ID: "12345",
                event: "open",
                title: "test123",
                startDate: "2024-05-21",
                endDate: "2024-06-27"
            }
        ]
    }
];

function flattenArray(array) {
    return array.reduce((acc, currentObj) => {
        Object.values(currentObj).forEach(nestedArray => {
            nestedArray.forEach(item => {
                // Check and correct inconsistencies in property names
// Do not perform this correction if unnecessary
                if (item.iD && !item.ID) {
                    item.ID = item.iD;
                    delete item.iD;
                }
                acc.push(item);
            });
        });
        return acc;
    }, []);
}

console.log(flattenArray(arr));

Answer №5

  1. Begin by creating a fresh array to store the outcomes.
  2. Iterate through each item within the original array.
  3. Access the property of each object, which happens to be an array.
  4. For every item in this array, go through them one by one.
  5. Generate a new object using the event data, including the month property obtained from the object key.
  6. Add this newly created object to the results array.

const arr = [ /* your initial array */ ];

const newArray = [];

arr.forEach(monthObject => {
  const month = Object.keys(monthObject)[0];
  monthObject[month].forEach(event => {
    const newEvent = { ...event,
      month: month.toUpperCase()
    };
    newArray.push(newEvent);
  });
});

console.log(newArray);

Based on the image you've provided, which demonstrates the desired format for transforming your data, it seems like you aim to convert an array of objects representing events.

const events = [ /* your original array */ ];

const getMonthName = (dateString) => {
  const date = new Date(dateString);
  return date.toLocaleString('default', {
    month: 'long'
  }).toUpperCase();
}

const updatedEvents = events.map(event => {
  return {
    ...event,
    month: getMonthName(event.startDate)
  };
});

console.log(updatedEvents);

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

Utilizing ng For in a personalized directive to fill a selection menu

I encountered an issue while trying to populate a selected dropdown using ngRepeat inside a custom directive. I came across this example that seemed similar to what I wanted to achieve here. Although it worked for the example, it didn't work for me. ...

Looking for assistance in adding some animated flair to your website as users scroll

I don't have much experience in animation but I would like to create some animation effects on scroll down. Can anyone provide suggestions? I attempted using SVG paths, but it didn't work out as expected. What I am aiming for is that when a visi ...

Struggling with jQuery fadeIn and fadeOut in IE8?

I am struggling to understand why my fadeIn, fadeOut, and corner() functions are not working in IE8 on my website at . They were functioning properly before, but now they seem to be broken. Can anyone pinpoint the issue causing this problem? If you click ...

Browsing JSON data to pinpoint locations on a Google map

Trying to create a google map using jQuery and javascript with latitude and longitude values stored in a JSON file. Clicking on a state name should generate the map. Encountering an issue where only index[0] is being generated. The for loop seems to be ma ...

Display or conceal toggle in ruby utilizing jQuery

I'm facing an issue with the functionality of a button that is meant to hide and show a form using jQuery. Initially, I added a path to signup in the button so that it would display and function properly. Now, when I click the button, the form shows u ...

Count up with style using the "jQuery Boilerplate" plugin for Jquery!

I am a beginner in creating jQuery plugins. The following jQuery plugin has been created using jQuery Boilerplate. It performs a count-up and notifies when the count-up is completed. I would like to have a function that restarts the count-up by setting t ...

Freezing Columns and Rows for a Spacious Scrollable Table

After extensive effort, I have been diligently striving to create a solution that allows a table's column headers to scroll with the body horizontally and the first column to scroll with the rows vertically. While I've come across solutions that ...

What could be causing an undefined error when running Javascript with Python and Selenium?

My goal is to utilize Javascript for retrieving a table body element on a webpage. Upon executing the script immediately, I receive an undefined response. However, if I introduce a few seconds delay, it functions correctly. def fetch_row_list(browser): ...

Cease the inclusion of the definition file import in the output of TS

I am facing an issue with a third-party library that needs to be dynamically loaded with an authentication key. Since the API is complex, I require type definitions in my TypeScript code for better clarity. In my .tsconfig file, I have set "target": "esn ...

JS Issue with Countdown functionality in Internet Explorer and Safari

I am having an issue with a JavaScript countdown not working on Internet Explorer and Safari, despite being tested on Windows 7. It works fine on Chrome and Firefox. I am unable to switch to a jQuery countdown due to certain restrictions on the website, so ...

Tips for retrieving all JavaScript source links from a website URL during page download

Is there a way to determine if a website is using a specific online JavaScript source, such as fontawesome? Some sources may only become apparent once they are actually loaded, rather than being visible in the website's source HTML. I attempted to us ...

Creating hashbang #! URL patterns for handling REST requests in client-side applications

I'm currently working on a single page application with my own custom router implementation. window.onhashchange = function(event) {... Within the URL structure, I am using hash bangs similar to the following examples: #!/products #!/products/1 #! ...

Unable to display icon using the fontawesome react-js library

import "./App.css"; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' function App() { return ( <div className="container"> <input type="text" className="form-control" placeholder ...

What is the process for adding an item to an object?

I currently have the following data in my state: fbPages:{'123':'Teste','142':'Teste2'} However, I am in need of a dynamic solution like the one below: async getFbPages(){ var fbPages = {} awa ...

What could be causing the erratic jumping behavior of the "newsletter sign-up" form within my modal dialog window?

On the homepage, there is a modal window that appears upon every pageload (it will be changed later), however, there seems to be an issue with the 'email sign up' form inside the window. The form seems to momentarily display at the top of the si ...

Decoding the enigma of addEventListener in Nuxt: Unveiling the "referenceError: window is not defined" issue

I am currently working on developing a hamburger menu, but I have encountered an error. The error message states: ReferenceError: window is not defined. The issue seems to be within the created section of the code. <script> export default { ...

Toggle the visibility of the left sidebar by hovering the mouse over it

How can I use CSS/JS to create a toggle function for my left sidebar on mouse hover? I want the Google iframe to display across the entire page when the mouse is in the middle, and the sidebar to appear with the Google iframe at a reduced size when the mou ...

Preserving User Login Details during Page Refresh in AngularJS

I am currently working on retaining user information even when the page refreshes. To achieve this, I have implemented the use of cookieStore in my Angular App. Here is how my run module looks like: .run(['$rootScope', '$cookieStore', ...

What should be the output when ending the process using process.exit(1)?

I need to update my code by replacing throw new Error('Unknown command.') with a log statement and process.exit(1);. Here is the example code snippet: private getCommandByName = (name: string): ICommand => { try { // try to fetch ...

Retrieving dynamically generated form components upon submission in a React application

I am facing an issue with a modal containing a dynamically rendered form in my React component. I want to gather all the user-entered field values and send them to the backend. Below is the code for rendering the dynamic form fields: import React from &ap ...