Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

codebullet's avatar

Help to reformat Array of objects with key from nested object value

Greetings

Please I need to reformat Array of objects in JavaScript The API requires the key of the array should be the identifier of the objects in the array which is the "id" value

Below is a snippet of available data and expected data

	
	//Data received
    tasks: [
      	{ id: 'task-1', content: 'Take out the garbage' },
  		{ id: 'task-2', content: 'Watch my favorite show' },
  		{ id: 'task-3', content: 'Charge my phone' },
   		{ id: 'task-4', content: 'Cook dinner' },
    ],

	//Expected data 
    tasks: {
      'task-1': { id: 'task-1', content: 'Take out the garbage' },
      'task-2': { id: 'task-2', content: 'Watch my favorite show' },
      'task-3': { id: 'task-3', content: 'Charge my phone' },
      'task-4': { id: 'task-4', content: 'Cook dinner' },
    },

Thanks so much in advance

0 likes
2 replies
tykus's avatar
tykus
Best Answer
Level 104

You can collect and keyBy, e.g.

collect($data)->keyBy('id')->all()

The data received is not valid JSON, so I don't know the original structure

1 like

Please or to participate in this conversation.