O
O
oskar barin2021-06-10 19:24:16
JavaScript
oskar barin, 2021-06-10 19:24:16

How to format an array of objects?

there is an array of objects

[
  {
    title: 'Tiger',
    weight: '90',
    category: {
      id: '333',
      name: 'heavy tank'
    }
  },  
  {
    title: 'Amx 50b',
    weight: '80',
    category: {
      id: '333',
      name: 'heavy tank'
    }
  },  
  {
    title: 'mt-25',
    weight: '25',
    category: {
      id: '444',
      name: 'light tank'
    }
  },  
  {
    title: 'Vickers Light 105',
    weight: '30',
    category: {
      id: '444',
      name: 'light tank'
    }
  }
]


output should be something like this
[
  { 
    category: {
      id: '444',
      name: 'light tank',
      tanks: [
        {
          title: 'Vickers Light 105',
          weight: '30',
        },
        {
         title: 'mt-25',
         weight: '25',
        }
      ]
    }
  },
  {
    category: {
      id: '333',
      name: 'heavy tank',
      tanks: [
        {
          title: 'Tiger',
          weight: '90'
        },        
        {
          title: 'Amx 50b',
          weight: '80',
        }
      ]
    }
  }
]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-06-10
@madrogalo

Object.values(arr.reduce((acc, { category, ...n }) => (
  (acc[category.id] ??= { ...category, tanks: [] }).tanks.push(n),
  acc
), {}))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question