-1

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

]
5
  • 2
    Please show your attempt Commented Apr 1, 2024 at 21:45
  • And there is no property 'month' in your expected output? Commented Apr 1, 2024 at 21:47
  • 1
    Looks an awful lot like Flattening deeply nested array of objects or How to flatten the nested array of of objects and duplicate the parent Commented Apr 1, 2024 at 21:48
  • Yea well if you dont need the months you can get that with a reduce and map on Object.values. Again, please show us your attempt. Commented Apr 1, 2024 at 21:54
  • 1
    arr.map(Object.values).flat(2); Commented Apr 1, 2024 at 22:02

5 Answers 5

2

arr.flatMap(Object.values).flat() will do the job:

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)

Sign up to request clarification or add additional context in comments.

Comments

2

If you don't need the months, but just want to flatten it, flatMap and flat() it :

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 add the month, thenreduce 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 }))))]), []);

Comments

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.

Comments

1

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));

Comments

0
  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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.