2020-12-31

JS convert Array of Objects into JSON GroupBy Format

I'm trying to find a way to convert the following array of objects into JSON

Original Format

const arr = [
  {
    userid: '1000080542',
    photoname: '2c8a4709-ed7e-00a50-0da4ead1de55118-f3-1473281639’,
    datetime: ‘2020-01-24T20:46:05+11:00’
  },
  {
    userid: '1000081532',
    photoname: '73321038-c8bf-57c6e-5d803cd0a920e9a-95-1487447082',
    datetime: ‘2020-01-24T20:46:05+11:00’
  },
  {
    userid: '1000081532',
    photoname: '5c00bc65-db1b-7a394-dd65b462b9e75e2-c5-1487447019',
    datetime: ‘2020-01-24T20:46:05+11:00’
  },
  {
    userid: '1000081532',
    photoname: '986ee1e2-2f8e-bf070-0d70d2e67537835-e2-1473821119',
    datetime: ‘2020-01-24T20:46:05+11:00’
  },
  {
    userid: '1000081532',
    photoname: '09f7cde6-68c8-f462d-c01f7713a2c747f-eb-1474294185',
    datetime: ‘2020-01-24T20:46:05+11:00’
  }
]

Converted Format

{
            1000080542: {
                '2c8a4709-ed7e-00a50-0da4ead1de55118-f3-1473281639': '2020-01-24T20:46:05+11:00',
                '73321038-c8bf-57c6e-5d803cd0a920e9a-95-1487447082': '2020-01-24T20:46:05+11:00'
            },
            1000081532: {
                '5c00bc65-db1b-7a394-dd65b462b9e75e2-c5-1487447019'': '2020-01-24T20:46:05+11:00',
                '986ee1e2-2f8e-bf070-0d70d2e67537835-e2-1473821119': '2020-01-24T20:46:05+11:00',
                '09f7cde6-68c8-f462d-c01f7713a2c747f-eb-1474294185': '2020-01-24T20:46:05+11:00'
            }
        }

I've been trying along these lines but I'm a big off

obj = arr.reduce((h, y) => {
  Object.keys(y).forEach(k => {
    if (!h[k]) {
      h[k] = []
      h[k].push(y[k])
    } else if (!h[k].includes(y[k])) h[k].push(y[k])
  })
  return h
}, {})
console.log(obj)

thanks



from Recent Questions - Stack Overflow https://ift.tt/3mYNhMt
https://ift.tt/eA8V8J

No comments:

Post a Comment