Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create new object array and merge objects into array object with same key value

This might seem a bit weird but I have a need to merge objects in an existing dataset into a new dataset grouped by a specific key value. Here’s the dataset:

const object = [
  {
    id: 1,
    scheduledAt: '2022-09-20',
    organization: {
      name: 'Organization 1'
    }
  },
  {
    id: 2,
    scheduledAt: '2022-09-10',
    organization: {
      name: 'Organization 2'
    } 
  },
  {
    id: 3,
    scheduledAt: '2022-09-20',
    organization: {
      name: 'Organization 3'
    }
  }
]

Here is what I am after as the return dataset:

const objectMerged = {
  '2022-09-20': [
    {
      id: 1,
      scheduledAt: '2022-09-20',
      organization: {
        name: 'Organization 1'
      }
    },
    {
      id: 3,
      scheduledAt: '2022-09-20',
      organization: {
        name: 'Organization 3'
      }
    }
  ],
  '2022-09-10': [
    {
      id: 2,
      scheduledAt: '2022-09-10',
      organization: {
        name: 'Organization 2'
      } 
    }
  ]
}

I have tried many different ways but nothing seems to work correctly. Here’s the latest code, which does not work:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const merged = []

object.forEach((item) => {
  if (!merged.length) {
    // if the return dataset is empty, add this item immediately
    merged.push({ [item.scheduledAt]: [item] }
  } else {
    // check if item already exists with the same scheduledAt as current object and if so, push it into that array as object
    // if does not exist, create new array entry with the new scheduledAt name

    const find = Object.keys(merged).map((k) => {
      console.log(`key ${k}`)
      console.log(merged[k])
    
      return Object.keys(merged[k]).map((key) => {
        console.log(`key2: ${key}`)
    
        return key === item.scheduledAt
      })
    })

    console.log(find)
  }
})

console.log(merged)

Any help is greatly appreciated. Thank you!

>Solution :

By using a reduce you can generate what you want. Please have a look:

const object = [
  {
    id: 1,
    scheduledAt: '2022-09-20',
    organization: {
      name: 'Organization 1'
    }
  },
  {
    id: 2,
    scheduledAt: '2022-09-10',
    organization: {
      name: 'Organization 2'
    } 
  },
  {
    id: 3,
    scheduledAt: '2022-09-20',
    organization: {
      name: 'Organization 3'
    }
  },
];

const objectMerged = object
  .sort((objectA, objectB) => 
    objectA.scheduledAt.localeCompare(objectB.scheduledAt)
  )
  .reduce((acc, cur) => ({
    ...acc,
    [cur.scheduledAt]: [
      ...(acc[cur.scheduledAt] || []),
      cur,
    ],
  }), {});

console.log(objectMerged);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading