我如何通过嵌套对象数组创建具有嵌套对象数组的对象

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

我正在处理这段数据,尝试使用 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"
}]

我想创建以下结构:(我想使用之前下一个对象的唯一模板值,如下所示)

{
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"},]
}

我将非常感谢我如何用函数或方法实现这一点的好主意。

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)

所以,你可以试试这个。但是你应该阅读数组方法。映射、缩减、过滤....

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

  return res
}, {})