简体   繁体   中英

Group objects if property values are the same

I'm trying to group the objects for the users that have the same location and type value shown in the example below. What would be the best way to approach this?

const diabetics = [
    {
        type: 'type 1',
        location: 'Boston'
        email: 'person1@gmail.com'
    },
    {
        type: 'type 2',
        location: 'New York'
        email: 'person2@gmail.com'
    },
    {
        type: 'type 1',
        location: 'Boston'
        email: 'person3@gmail.com'
    },
    {
        type: 'type 1',
        location: 'Maine'
        email: 'person4@gmail.com'
    },
]

// expected output 
const diabetics = [
    {
        type: 'type 1',
        location: 'Boston'
        email: [
        'person1@gmail.com',
        'person3@gmail.com'
        ]
    },
    {
        type: 'type 2',
        location: 'New York'
        email: 'person2@gmail.com'
    },
    {
        type: 'type 1',
        location: 'Maine'
        email: 'person4@gmail.com'
    },
]

You could also get the result using Array.reduce() , creating groups using a key composed of type and location .

Once we have a map keyed on type and location we can use Array.values() to return the desired result:

 const diabetics = [ { type: 'type 1', location: 'Boston', email: 'person1@gmail.com' }, { type: 'type 2', location: 'New York', email: 'person2@gmail.com' }, { type: 'type 1', location: 'Boston', email: 'person3@gmail.com' }, { type: 'type 1', location: 'Maine', email: 'person4@gmail.com' }, ] const result = Object.values(diabetics.reduce ((acc, { type, location, email }) => { // Create a grouping key, in this case using type and location... const key = [type, location].join("-"); acc[key] ||= { type, location, email: [] }; acc[key].email.push(email); return acc; }, {})) console.log('Result:', result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM