Casting an Array with Numeric Keys as an Object

Casting an Array with Numeric Keys as an Object

Yes, they are just locked away unless cast back to an array. There are a few little "Gotchas" in PHP, for example in older versions you could define a constant as an array, but then never access its elements. Even now you can define a constant as a resource (e.g., define('MYSQL',mysql_connect());) although this leads to rather unpredictable behavoir and, again, should be avoided.

Generally, it's best to avoid array-to-object casts if at all possible. If you really need to do this, consider creating a new instance of stdClass and then manually renaming all the variables, for example to _0, _1, etc.

$a = array('cat','dog','pheasant');
$o = new stdClass;
foreach ($a as $k => $v) {
if (is_numeric($k)) {
$k = "_{$k}";
}
$o->$k = $v;
}

EDIT: Just did one more quick test on this hypothesis, and yes, they officially "do not exist" in object context; the data is stored, but it's impossible to access, and is therefore the ultimate private member. Here is the test:

$a = array('one','two','three');
$o = (object)$a;
var_dump(property_exists($o, 1), property_exists($o, '1'));

And the output is:

bool(false)
bool(false)

EDIT AGAIN: Interesting side-note, the following operation comes back false:

$a = array('one','two','three','banana' => 'lime');
$b = array('one','two','banana' => 'lime');

$y = (object)$a;
$z = (object)$b;

var_dump($y == $z);

Converting JavaScript object with numeric keys into array

It's actually very straight forward with jQuery's $.map

var arr = $.map(obj, function(el) { return el });

FIDDLE

and almost as easy without jQuery as well, converting the keys to an array and then mapping back the values with Array.map

var arr = Object.keys(obj).map(function(k) { return obj[k] });

FIDDLE

That's assuming it's already parsed as a javascript object, and isn't actually JSON, which is a string format, in that case a run through JSON.parse would be necessary as well.

In ES2015 there's Object.values to the rescue, which makes this a breeze

var arr = Object.values(obj);

Javascript array reduce convert array to object with integer keys

For your purposes (using material-table), your current objects will work fine. {1:"wheat"} is effectively the same as {"1":"wheat"}.

Unquoted property names / object keys in JavaScript gives a very detailed explanation of why. In short, numeric property names can be used, but they will be coerced into strings.

Convert part of an Object from numeric keys to Array in Javascript

You can recursively reduce the object to new object, and convert each object that has the key 0 to an array using Object.values():

const demo = {a:'b', c:{0:{id:'one'},1:{id:'two'}}, d:{0:{country: {0:{name:'mx'},1:{name:'usa'}} }} };

const arrayfy = (o) => Object.entries(o)

.reduce((r, [k, v]) => {

if(typeof v === 'object') {

const t = arrayfy(v);

r[k] = '0' in v ? Object.values(t) : arrayfy(t);

} else {

r[k] = v;

}



return r;

}, {});



const result = arrayfy(demo);

console.log(result);

PHP array with numeric keys as string can't be used

So, I haven't seen any other answers touch upon this, but @xdazz came close.

Let's start our environment, $obj equals the object notation of a decoded string:

php > $obj = json_decode('{"1":1,"2":2}');

php > print_r($obj);
stdClass Object
(
[1] => 1
[2] => 2
)

php > var_dump( $obj );
object(stdClass)#1 (2) {
["1"]=>
int(1)
["2"]=>
int(2)
}

If you want to access the strings, we know the following will fail:

php > echo $obj->1;

Parse error: parse error, expecting `T_STRING' or `T_VARIABLE' or `'{'' or `'$'' in php shell code on line 1

Accessing the object variables

You can access it like so:

php > echo $obj->{1};
1

Which is the same as saying:

php > echo $obj->{'1'};
1

Accessing the array variables

The issue with arrays is that the following return blank, which is the issue with typecasting.

php > echo $obj[1];
php >

If you typecast it back, the object is once again accessible:

php > $obj = (object) $obj;
php > echo $obj->{1};
1

Here is a function which will automate the above for you:

function array_key($array, $key){
$obj = (object) $array;
return $obj->{$key};
}

Example usage:

php > $obj = (array) $obj;
php > echo array_key($obj, 1);
1

php > echo array_key($obj, 2);
2

Convert Array into Object of Keys and Values using javascript/jquery

You can use a simple for loop to do it

var array = [
["id1", "parent1", "name1", "desc1"],
["id2", "parent1", "name2", "desc2"],
["id3", "parent1", "name3", "desc3"]
];

const obj = {}
for (const item of array) {
obj[item[0]] = item[2];
}

console.log(obj);

Convert array to object keys

try with Array#Reduce

const arr = ['a','b','c'];
const res = arr.reduce((acc,curr)=> (acc[curr]='',acc),{});
console.log(res)

How to convert an array with one object and multiple keys into an array of multiple objects using those keys and their values?

You were pretty close. All you needed to do is specify the name:

const data = {
"category": "None",
"ARFE": 553.5,
"BV": 900,
"RF rfeer": 0
};

const result = Object
.entries(data)
.filter(([_, value]) => typeof value === 'number')
.map(([key, value]) => ({ name: key, value }));

console.log(result);


Related Topics



Leave a reply



Submit