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

raidboss's avatar

GroupBy JSON JavaScript

I have the following json object

[
		{
				'Book': {
						'ID': 1
						'Name': 'Book1'
				},
				'Author_ID' : 1
		},
		{
				'Book': {
						'ID': 5,
						'Name': 'Book5'
				},
				'Author_ID' : 1
		},
		{
				'Book': {
						'ID': 6,
						'Name': 'Book6'
				},
				'Author_ID' : 2
		},
		{
				'Book': {
						'ID': 2,
						'Name': 'Book2'
				},
				'Author_ID' : 2
		},
]

And I need to parse the JSON to look like this

[
		{
				'Author_ID':  1,
				'Books': [
						{
								'ID': 1
								'Name': 'Book1'
						},
						{
								'ID': 5
								'Name': 'Book5'
						},
				]
		},
		{
				'Author_ID':  2,
				'Books': [
						{
								'ID': 6
								'Name': 'Book6'
						},
						{
								'ID': 2
								'Name': 'Book2'
						},
				]
		}
]

I can't really begin to tackle this problem, so any help would be appreciated!

Thank you for reading :)

0 likes
3 replies
JakeCausier's avatar

You could do it with the following structure:

// Decode the JSON into a PHP array, then into a Laravel collection object
$data = collect(json_decode($json, true));

// Group the items by their author, then remap the structure to gather the books from each item using pluck()
$data->groupBy('Author_ID')
	->map(function ($author, $index) {
		return [
			'Author_ID' => $index,
			'Books' => $author->pluck('Book')->toArray(),
		]
	})
	->values()
	->toArray();
JakeCausier's avatar

I wrote this out in PHP, but it can also be done easily in JavaScript using a library such as lodash to get access to a similar groupBy function

Tray2's avatar

Where do you get the data from?

Is it your own database or is it some external API.

If it's the first you really should do the grouping in the database.

Please or to participate in this conversation.