Home > Software design >  an array of objects merge with if condition
an array of objects merge with if condition

Time:04-19

I'm trying to merge an array of objects after a condition is true. I tried to use the reducer function, but I'm not sure that is the right way.

This is my array of objects:

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

What I want to do here, is that if the Profile number is the same, they should merge like this:

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

How I should approach this?

Many Thanks,

CodePudding user response:

I suggest you a solution with a different result than you expect. I think it would be better.

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

  • Related