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

vincent15000's avatar

Equivalent PHP -> JS to access to an object property from a variable

Hello,

I'm looking for an equivalent of this code.

$contact = 'name';
$name = $contact->$property;

Here the JS array of objects (generated by Laravel, perhaps there is something to do in the backend to have the right format ?).

[ { "id": 6, "name": "Alphonse Fontaine" }, { "id": 7, "name": "Véronique Courtois" } ]

This works only if I have an array with keys, but doesn't work with an object.

property = 'name';
name = contact[property];

But when I write this, it works.

property = 'name';
name = contact.name;

So I'd like to write something like this.

property = 'name';
name = contact.property;

Can you help me please ? ;)

Thanks a lot.

V

0 likes
4 replies
ramonrietdijk's avatar
Level 30

Although an object is not an array, you still should be able to access it via brackets.

const contact = {
    name: "Alphonse Fontaine"
}

const property = "name"

console.log(contact[property])

Or did I misunderstood?

1 like
jlrdw's avatar
data[0].name

If using data as the variable. But if more than one row you have to iterate with a count variable such as i.

I admit I am not totally sure what you are trying to do. But looping over json is not that hard.

1 like
vincent15000's avatar

@ramonrietdijk @michaloravec @jlrdw Sure I'm tired ... I use a custom component where I can customized the property value. I set it to fullname instead of name. Effectively I already have the right way to do what I need. Sorry ... I go and sleep ;).

1 like

Please or to participate in this conversation.