Working with array of object in javascript

I have an issue while i’m working with cluster of items in Javascript.

The issue: input
{Code}

[
    {  
        "artistName": "NgaNguyen Duy",
        "workId": "554a9e4fa36f794b31000024"
    }, 
    {
        "artistName": "NgaNguyen Duy",
        "workId": "554d3ffbcc477a7110000003"
    },
    {
        "artistName": "Kristin",
        "workId": "557a4kfbcc5e2a7110000223"
    }
    ]

And output should be:

[
{
    "artistName": "NgaNguyen Duy",
    "workId"    : ["554a9e4fa36f794b31000024", "554d3ffbcc477a7110000003"]
},
{
    "artistName": "Kristin",
    "workId": ["557a4kfbcc5e2a7110000223"]
}
]

As a starting point, I have split the problem into two.

First merging the workId’s. For this I have used an object. We loop through the original collection and look to see if the target object (mergedObjCollection) has a key name matching the artist name. If not, we create a key of artist name and assign an empty array. We then push the workid to that array.

const collection = [
    {  
        "artistName": "NgaNguyen Duy",
        "workId": "554a9e4fa36f794b31000024"
    }, 
    ...
]
const mergedObjCollection = {}

for (let {artistName, workId} of collection) {

  if (!mergedObjCollection[artistName]) {
    mergedObjCollection[artistName] = []
  }
  
  mergedObjCollection[artistName].push(workId)
}

Output:

{
  Kristin: ['557a4kfbcc5e2a7110000223'],
  NgaNguyen Duy: (2) ['554a9e4fa36f794b31000024', '554d3ffbcc477a7110000003']
}

We can now convert that back to their respective objects.

const mergedCollection = []

for (let [artistName, workId] of Object.entries(mergedObjCollection)) {
  mergedCollection.push({artistName, workId})
}

Output:

[
  {
     artistName: "NgaNguyen Duy",
     workId: (2) ['554a9e4fa36f794b31000024', '554d3ffbcc477a7110000003']
  },
  {
     artistName: "Kristin",
     workId: ['557a4kfbcc5e2a7110000223']
  }
]

The following links maybe useful reading :slight_smile:

Destructuring Assignment

Edit: The above combined into a function

function mergeWorkIds(collection) {
  const mergedWorkIds = {}

  for (let {artistName, workId} of collection) {
  
    if (!mergedWorkIds[artistName]) mergedWorkIds[artistName] = []
    
    mergedWorkIds[artistName].push(workId)
  }
  
  return Object
    .entries(mergedWorkIds)
    .map(([artistName, workId]) => ({artistName, workId}))
}
3 Likes

Extremely helpful! Thank you for your support, it was easy to understand. Have a good time

1 Like