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

devsam247's avatar

Get property of object javascript by name

Here is the data for the object from Laravel controller

(2) [{…}, {…}]
0
: 
{id: 4, created_at: '2022-12-13T17:07:50.000000Z', updated_at: '2022-12-13T17:07:50.000000Z', test_id: 3, question: 'Which of the following is not a variable option for split testing?', …}
1
: 
{id: 5, created_at: '2022-12-13T17:07:50.000000Z', updated_at: '2022-12-13T17:07:50.000000Z', test_id: 3, question: 'How many pixels can you have?', …}
length
: 
2
[[Prototype]]
: 
Array(0)

This is the loop statement I used to output the property of each object

  displayQuiz();

        function displayQuiz(){
            
            const questions = @json($response->que_ans);
            console.log(questions)
            for (question in questions) {
                console.log(`${question}`); //This Output the number for each object
                console.log(question['question']); //This output undefined

                for(item of question){
                    console.log(item.question); //This output undefined
                }
            }
          
        }

I seem not to be able to access the property of each object, please what I'm I missing?

0 likes
1 reply
kokoshneta's avatar

Your data looks… weird. It’s certainly not valid JSON the way you’ve pasted it here, so it’s hard to know what to do with it. What is (2) [{…}, {…}] supposed to mean? Or [[Prototype]]? And what is Array(0) doing at the end?

IF the actual structure of your data is this:

[
	{
		"id": 4,
		"created_at": "2022-12-13T17:07:50.000000Z",
		"updated_at": "2022-12-13T17:07:50.000000Z",
		"test_id": 3,
		"question": "Which of the following is not a variable option for split testing?"
	},
	{
		"id": 5,
		"created_at": "2022-12-13T17:07:50.000000Z",
		"updated_at": "2022-12-13T17:07:50.000000Z",
		"test_id": 3,
		"question": "How many pixels can you have?"
	}
]

– then iterating through it should be fairly easy:

for (q in questions) {
	console.log(q.question);
}

Please or to participate in this conversation.