Home > Mobile >  How i can create object with nested arrays of objects by array of nested objects
How i can create object with nested arrays of objects by array of nested objects

Time:03-18

i struggle with this piece of data, trying to convert it using javascript:

[{
    rawCol: "personalemail",
    template: "CONTACTS",
    modifiedCol: "URL"
}, {
    rawCol: "personId",
    template: "CONTACTS",
    modifiedCol: "PERSONCODE"
}, {
    rawCol: "ssn",
    template: "VITALS",
    modifiedCol: "IDENTITY"
}, {
    rawCol: "gender",
    template: "VITALS",
    modifiedCol: "GENDERCODE"
}, {
    rawCol: "ethnic",
    template: "VITALS",
    modifiedCol: "ETHNICCODE"
}, {
    rawCol: "birthdate",
    template: "VITALS",
    modifiedCol: "BIRTHDATE"
},  {
    rawCol: "contactType",
    template: "OTHER",
    modifiedCol: "NETCONTACTTYPE"
}, {
    rawCol: "workemail",
    template: "OTHER",
    modifiedCol: "EMAILADDRESS"
}]

I want to create the following structure: (I want to use the unique template values from the previous nexted objects, as follows)

{
CONTACTS: [
{rawFile: "personalemail", modifiedCol: "URL"},
{rawFile: "personId", modifiedCol: "PERSONCODE"}
],
VITALS: [
{rawFile: "ssn", modifiedCol: "IDENTITY"},
{rawFile: "gender", modifiedCol: "GENDERCODE"},
{rawFile: "ethnic", modifiedCol: "ETHNICCODE"},
{rawFile: "birthdate", modifiedCol: "BIRTHDATE"},
],
OTHER: [
{rawFile: "contactType", modifiedCol: "NETCONTACTTYPE"},
{rawFile: "workemail", modifiedCol: "EMAILADDRESS"},]
}

I will be very thankful for a good idea how i can achieve this with a function or method.

CodePudding user response:

const arr = [{
        rawCol: "personalemail",
        template: "CONTACTS",
        modifiedCol: "URL"
    }, {
        rawCol: "personId",
        template: "CONTACTS",
        modifiedCol: "PERSONCODE"
    }, {
        rawCol: "ssn",
        template: "VITALS",
        modifiedCol: "IDENTITY"
    }, {
        rawCol: "gender",
        template: "VITALS",
        modifiedCol: "GENDERCODE"
    }, {
        rawCol: "ethnic",
        template: "VITALS",
        modifiedCol: "ETHNICCODE"
    }, {
        rawCol: "birthdate",
        template: "VITALS",
        modifiedCol: "BIRTHDATE"
    },  {
        rawCol: "contactType",
        template: "OTHER",
        modifiedCol: "NETCONTACTTYPE"
    }, {
        rawCol: "workemail",
        template: "OTHER",
        modifiedCol: "EMAILADDRESS"
    }];
    
    const data = {};
    arr.forEach((ar) => {
        data[ar.template] =  [...(data[ar.template] || []), {rawFile: ar.rawCol, modifiedCol: ar.modifiedCol}]
    });
    
    console.log(data)

CodePudding user response:

So, u can try this one. But u should read the array methods. map, reduce, filter ....

const expectation = data.reduce((res, elem) => {
  const val = elem?.template
  delete elem.template
  if (!res[val]) res[val] = []
  res[val].push(elem)

  return res
}, {})
  • Related