1

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,

Zoltan
  • 15
  • 4
  • 1
    _"I tried to use the reducer function"_ - Where's that attempt? _"but I'm not sure that is the right way"_ - If it works it's the _"right way"_. – Andreas Apr 14 '22 at 14:14
  • 2
    Instead of creating additional properties like name2, color2, etc, consider grouping the matching elements into arrays. See for example https://stackoverflow.com/questions/40774697/how-can-i-group-an-array-of-objects-by-key – James Apr 14 '22 at 14:19
  • Thank you @James, your comment was helpful to get a direction – Zoltan Apr 14 '22 at 16:26

1 Answers1

2

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; }
A1exandr Belan
  • 4,442
  • 3
  • 26
  • 48