Home > Software engineering >  Looping over array of object
Looping over array of object

Time:09-19

I have an array of objects, trying to create a new array

 a=[
    {
        sessionID: '1',
        timestamp: '2022-06-26T05:47:00.794Z',
        taskName: 'abc'
    },
    {
        sessionID: '1',
        timestamp: '2022-06-26T05:47:21.626Z',
        taskName: 'def'
    },
    {
        sessionID: '1',
        timestamp: '2022-06-26T05:47:21.626Z',
        taskName: 'ghi'
    },
    {
        sessionID: '1',
        timestamp: '2022-06-26T05:47:21.626Z',
        taskName: 'jkl'
    },
    {
        sessionID: '2',
        timestamp: '2022-06-26T11:01:48.499Z',
        taskName: '123'
    },
    {
        sessionID: '2',
        timestamp: '2022-06-26T11:28:07.389Z',
        taskName: '456'
    }
]

trying to create a new array based on session ID [abc<<def<<ghi<<jkl,123<<456]

CodePudding user response:

lets group array of objects by something using reduce method.

var a = [{sessionID:"1",timestamp:"2022-06-26T05:47:00.794Z",taskName:"abc"},{sessionID:"1",timestamp:"2022-06-26T05:47:21.626Z",taskName:"def"},{sessionID:"1",timestamp:"2022-06-26T05:47:21.626Z",taskName:"ghi"},{sessionID:"1",timestamp:"2022-06-26T05:47:21.626Z",taskName:"jkl"},{sessionID:"2",timestamp:"2022-06-26T11:01:48.499Z",taskName:"123"},{sessionID:"2",timestamp:"2022-06-26T11:28:07.389Z",taskName:"456"}];

var result = Object.values(a.reduce(function(agg, item) {
  agg[item.sessionID] = agg[item.sessionID] || [];
  agg[item.sessionID].push(item.taskName)
  return agg
}, {})).map(function(item) {
  return item.join("<<<");
})
console.log(result)

  • Related