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

Enea74's avatar

Api resource: getting array of objects instead of object of objects

I have a model that looks like:

	    "id" => 1,
		"name" => "Name",
		"options" => [
				"option_33423" => [
						"text" => "Lorem ipsum"
				], 
				"option_33222" => [
						"text" => "Lorem ipsum"
				], 
		]

problem is, when I transform the object through the API resource, I have an output like this:

	    "id": 1,
		"name":  "Name",
		"options" : {
				"option_33423" : {
						"text": "Lorem ipsum"
				}, 
				"option_33222": {
						"text": "Lorem ipsum"
				}, 
		}

Because the frontend should cycle through the options, it would be easier to have an array of objects with the original key names, i.e.:

	    "id": 1,
		"name":  "Name",
		"options" : [
				"option_33423"  => {
						"text": "Lorem ipsum"
				}, 
				"option_33222": => {
						"text": "Lorem ipsum"
				}, 
		]

I couldn't find an answer in the documentation, any hint?

0 likes
2 replies
tykus's avatar

This is not valid JSON; there is no => syntax in JSON:

	    "id": 1,
		"name":  "Name",
		"options" : [
				"option_33423"  => {
						"text": "Lorem ipsum"
				}, 
				"option_33222": => {
						"text": "Lorem ipsum"
				}, 
		]

Whenever you convert a PHP associative array to JSON (such as the Resource does), you get an Object. If you wan options as an array, you sacrifice the keys.

1 like
SilenceBringer's avatar

@enea74 I think you have misunderstanding about arrays in js. Arrays can have only numeric keys in sequence (0, 1, 2, etc.). Any other keys (including keys not in sequence, or string keys) will be treated as objects by js

So, in you case, if you vant options to be an array - you need to move name of option inside of it, like

"options" : [
				{
						"name": "option_33423",
						"text": "Lorem ipsum"
				}, 
				{
						"name": "option_33222",
						"text": "Lorem ipsum"
				}, 
		]

this way options is array of objects with available option details

1 like

Please or to participate in this conversation.