-3

How do you group an array of objects by an object key to create a new array list of objects based on the grouping? For example, I have an array of objects:

 {
       "List": [
          {
             "column1": "Name",
              "column2" :"Gender",
              "column3" :"Phone",
              "column4" :'Age',
             "items": [
                {
                   "column1": "SR",
                   "column2" :"M",
                   "column3" :"1223322",
                    "column4" :'23',
                },
                {
                   "column1": "SA",
                   "column2" :"F",
                   "column3" :"1322222",
                    "column4" :'26',
                },
             ]
          }

and my expected output :

List :[
{
               "Name": "SR",
              "Gender" :"M",
              "Phone" :"1223322",
              "Age" :'23',
    {...}
    ]

I dont know how to map this ? Please help me to resolve. Thanks

Always Learn
  • 662
  • 6
  • 14
  • 1
    Why is `"List"` an array? are there going to be multiple entries in that array, each with their own "items" array inside? – Andrew Parks Feb 16 '23 at 17:39
  • And adding more to @AndrewParks's question, would the objects in the array "List" always have the same keys, "column1", "column2" etc ..? – Sudhansu Choudhary Feb 16 '23 at 17:44

1 Answers1

1

Use dynamic property access to convert the column names in the original items based on the mappings in the containing object.

Use .flatMap() to flatten the array of objects with nested items arrays into a single array of items.

const data = {
  "List": [{
    "column1": "Name",
    "column2": "Gender",
    "column3": "Phone",
    "column4": 'Age',
    "items": [{
        "column1": "SR",
        "column2": "M",
        "column3": "1223322",
        "column4": '23',
      },
      {
        "column1": "SA",
        "column2": "F",
        "column3": "1322222",
        "column4": '26',
      },
    ]
  }]
};

data.List = data.List.flatMap(d =>
  d.items.map(item =>
    Object.fromEntries(Object.entries(item).map(([key, value]) => [d[key], value]))));

console.log(data);
Barmar
  • 741,623
  • 53
  • 500
  • 612