Flattening nested JSON data with array

I have a Formik form containing 3 fields, MemberMemberID, EventEventID and event_date. The form content represents an event (e.g. a Tuesday club) occurring on a specific date, attended by a list of members.

Formik captures the data in a variable, formatting the form data in key value pairs as follows:

ScreenGrab

Console logging the same Formik variable via JSON.stringify gives:

    {"MemberMemberId":["1","2"],"EventEventId":"1","event_date":"20000102"}

So I think what I am looking at is an object, containing an array (MemberMemberId).

To pass this data to my database, I need the data in separate rows, as follows:

    {"MemberMemberId":"1","EventEventId":"1","event_date":"20000102"}
    {"MemberMemberId":"2","EventEventId":"1","event_date":"20000102"}

To be clear, in my example there are two rows, but there can be many members attending an event on a given date.

I am struggling with how I can separate out this nested data into individual rows. I was looking at using forEach to do this with the code below, but that is not working for a couple of reasons: firstly, because the data from Formik is not in an array itself, so it throws a TypeError: values.forEach is not a function error.

          //const values1 = [{MemberMemberId:["3","4"],
          //                EventEventId:"1",
          //                  event_date:"20000102"}]
          

         const result=[]
          values.forEach((o)=>{
            o.MemberMemberId.forEach((MemberId)=>{
              result.push({
                "MemberMemberId" : o.MemberMemberId,
                "EventEventId" : o.EventEventId,
                "event_date" : o.event_date,
              });
              // console.log('o.membermemberid = ' +o.MemberMemberId)
            });
          });

And, secondly, if the first problem could be overcome (I achieved this for testing purposes using the dummy variable values1 commented out in my code above), then my code is still not right. It generates two rows, but MemberMemberId is still an array, as follows:

   [{"MemberMemberId":["3","4"],"EventEventId":"1","event_date":"20000102"},
    {"MemberMemberId":["3","4"],"EventEventId":"1","event_date":"20000102"}]

I presume this is because the line "MemberMemberId" : o.MemberMemberId, in my code isn’t referring to a single element of that array correctly, but I’m not sure how to correct that – I think I could do it if the array contained key-value/pairs by referring to the key, but I’m not sure how to do it with it just containing values.

Any help on these two issues would be appreciated. Whether that’s guidance on how to resolve the errors with the approach I’ve been trying, or suggesting an alternative approach instead.

>Solution :

const input = {"MemberMemberId":["1","2"],"EventEventId":"1","event_date":"20000102"}

const output = input.MemberMemberId.map(id => ({
  ...input,
  MemberMemberId: id
}))

console.log(output)

Leave a Reply