skip to Main Content

I have an array of objects having multiple 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"
            }
        ]
    }
]

Output I need

   [
    {
        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"
    }

]

4

Answers


    1. Initialize a new array to hold the results.
    2. Loop through each object in the original array.
    3. For each object, access its property (which is an array).
    4. Loop through each event in this array.
    5. Create a new object from the event, adding the month property from the key of the object.
    6. Push this new object to the results array.
    const arr = [ /* your original 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 shows the desired output format for your data transformation, it appears you want to convert an array of objects that represent 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);
    Login or Signup to reply.
  1. One possible way to do it (not the most readable if you’re not familiar with those) is to use reduce and concat like this:

    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 allows you to loop over an array and to aggregate data into an accumulator. In this case, the accumulator is your result array.

    Login or Signup to reply.
  2. Another option is to reduce the array and flatMap each Object.keys with an 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 an one-liner":

    const res = arr.reduce((p, c) => ([ ...p,...(Object.keys(c).flatMap(month => c[month].map(o => ({ ...o, month }))))]), []);
    
    Login or Signup to reply.
  3. You can use a reduce function to flatten your function:

    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 => {
                    // Not sure if it was a mistake or intended to have "iD" and "ID". 
    // If not just skip this fix
                    if (item.iD && !item.ID) {
                        item.ID = item.iD;
                        delete item.iD;
                    }
                    acc.push(item);
                });
            });
            return acc;
        }, []);
    }
    
    console.log(flattenArray(arr));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search