对象数组与 if 条件合并

an array of objects merge with if condition

我正在尝试在条件为真后合并一组对象。 我尝试使用 reducer 功能,但我不确定这是正确的方法。

这是我的对象数组:

[
    {
        "Profile number": "S12",
        "Line Number": "5874",
        "Name": "Pillow",
        "Color": "White",
    },
    {
        "Profile number": "S12",
        "Line Number": "5874",
        "Name": "Blanket",
        "Color": "Blue",
    },
  {
        "Profile number": "S12",
        "Line Number": "5874",
        "Name": "Pillowcase",
        "Color": "White",
    },
    {
        "Profile number": "S41",
        "Line Number": "8730",
        "Name": "Curtain",
        "Color": "White",
    }
]

我想在这里做的是,如果 个人资料编号 相同,它们应该像这样合并:

[
  {
    "Profile number": "S12",
    "Line Number": "5874",
    "Name": "Pillow",
    "Color": "White",
    "Name2": "Blanket",
    "Color2": "Blue",
    "Name3": "Pillowcase",
    "Color3": "White",
  },
  {
    "Profile number": "S41",
    "Line Number": "8730",
    "Name": "Curtain",
    "Color": "White",
  }
]

我该如何处理?

非常感谢,

我建议您采用与预期结果不同的解决方案。我觉得会更好。

const data=[{"Profile number":"S12","Line Number":"5874",Name:"Pillow",Color:"White"},{"Profile number":"S12","Line Number":"5874",Name:"Blanket",Color:"Blue"},{"Profile number":"S12","Line Number":"5874",Name:"Pillowcase",Color:"White"},{"Profile number":"S41","Line Number":"8730",Name:"Curtain",Color:"White"}];

const result = Object.values(data.reduce((acc, { 'Profile number': profileNumber, 'Line Number': lineNumber, Name, Color }) => {
    acc[profileNumber] ??= { profileNumber, lineNumber, names: [], colors: [] };
    acc[profileNumber].names.push(Name);
    acc[profileNumber].colors.push(Color);
    
    return acc;
}, {}));

console.log(result);

// [{
//    "profileNumber": "S12",
//    "lineNumber": "5874",
//    "names": ["Pillow", "Blanket", "Pillowcase"],
//    "colors": ["White", "Blue","White"]
//  },
//  {
//    "profileNumber": "S41",
//    "lineNumber": "8730",
//    "names": ["Curtain"],
//    "colors": ["White"]
//  }]
.as-console-wrapper { max-height: 100% !important; top: 0; }