To dynamically access an object's property: Use keyof typeof obj as the type of the dynamic key, e.g. type ObjectKey = keyof typeof obj; . Use bracket notation to access the object's property, e.g. obj[myVar] .
Access JavaScript Object Properties & Methods An object's properties can be accessed using the dot notation obj. property-name or the square brackets obj["property-name"] .
<?php
$x = new StdClass();
$x->{'todo-list'} = 'fred';
var_dump($x);
So, $object->{'todo-list'}
is the sub-object. If you can set it like that, then you can also read it the same way:
echo $x->{'todo-list'};
Another possibility:
$todolist = 'todo-list';
echo $x->$todolist;
If you wanted to convert it to an array, which can be a little more easily (ie the obvious $ret['todo-list']
accessing), this code is taken almost verbatim from Zend_Config and will convert for you.
public function toArray()
{
$array = array();
foreach ($this->_data as $key => $value) {
if ($value instanceof StdClass) {
$array[$key] = $value->toArray();
} else {
$array[$key] = $value;
}
}
return $array;
}
Try this simplest way!
$obj = $myobject->{'mydash-value'};
$objToArray = array($obj);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With