Home > front end >  how can i group values of nested objects into array?
how can i group values of nested objects into array?

Time:08-24

Does anyone know a way to group each value of nested objects into array by an object key? For example, I have an array of member objects and I want to group each object by 'city' and values should be array type:

const members =
  {
     { 'abc123' : {
                     'name' : 'James'
                     'city' : 'New York'
                     'age'  : 43
                  }
     },
     { 'cdb143' : {
                     'name' : 'Jackson'
                     'city' : 'Los Angeles'
                     'age'  : 25
                  }
     },
     { 'asf162' : {
                     'name' : 'Lucas'
                     'city' : 'Los Angeles'
                     'age'  : 32
                  }
     },
     { 'cdb143' : {
                     'name' : 'Caden'
                     'city' : 'New York'
                     'age'  : 27
                  }
     },
     { 'cdb143' : {
                     'name' : 'Mason'
                     'city' : 'Los Angeles'
                     'age'  : 25
                  }
     },
     { 'cdb143' : {
                     'name' : 'Logan'
                     'city' : 'New York'
                     'age'  : 33
                  }
     },

  }

and this should be:

const result = 
{
  {
  'New York': {
                'name':['James', 'Caden', 'Logan']
                'age' :[43, 27, 33]
              }
  },
  {
  'Los Angeles': {
                'name':['Jackson', 'Lucas', 'Mason']
                'age' :[25, 32, 25]
              }
  }
}

Any suggestion would be appreciated. Thank you

CodePudding user response:

To achieve this I just iterated through the values of each member and pushed their name and age to arrays in a Map keyed by each city. To create the desired output schema, I just mapped over the entries, creating a new object for each city.

const members = [
    { abc123: { name: 'James', city: 'New York', age: 43 } },
    { cdb143: { name: 'Jackson', city: 'Los Angeles', age: 25 } },
    { asf162: { name: 'Lucas', city: 'Los Angeles', age: 32 } },
    { cdb143: { name: 'Caden', city: 'New York', age: 27 } },
    { cdb143: { name: 'Mason', city: 'Los Angeles', age: 25 } },
    { cdb143: { name: 'Logan', city: 'New York', age: 33 } },
];

function group(members) {
    const result = new Map();
    for (const { city, name, age } of members.flatMap((member) => Object.values(member))) {
        if (!result.has(city)) result.set(city, { name: [], age: [] });
        result.get(city).name.push(name);
        result.get(city).age.push(age);
    }
    return Array.from(result.entries()).map(([city, info]) => ({ [city]: info }));
}

console.log(group(members));

  • Related