Notes
One implementation below operates in PHP style (as a function), and another adds array_change_key_case() as a method to the Object class, so that it can be used on any object.
In either case, an object will be used instead of an array, since in JavaScript, an array is only for numerically indexed arrays, and "key case" implies an associative array, which, in JavaScript, is generally an "Array-like object" (requires, unlike a real JS Array, however, any "length" property to be manually set). (Could facilitate array-like usage by auto-updating "length" attribute within these array-like functions?)
As a Function (PHP-style)
// "case", while used in PHP docs, is a reserved word, so using "casing"
const CASE_UPPER = 1;
const CASE_LOWER = 0;
function array_change_key_case(/* array */ input, /*[, int ]*/ casing) {
// In case const is not allowed/used
if (casing === "CASE_UPPER") casing = 1;
else if (casing === "CASE_LOWER") casing = 0;
else if (casing === undefined) {
casing = 0;
}
for (a in input) {
if (a !== "length") {
var temparr = input[a];
delete(input[a]);
if (casing) {
input[a.toUpperCase()] = temparr;
}
else {
input[a.toLowerCase()] = temparr;
}
}
}
}
Example JavaScript Usage
var arr = {dOgYears:"7", hUmanYears:"1"};
arr.length = 2;
array_change_key_case(arr, CASE_UPPER);
for (abc in arr) {
print(abc);
print(arr[abc]);
}
Output
length 2 DOGYEARS 7 HUMANYEARS 1
As a Method (JavaScript-style)
// "case", while used in PHP docs, is a reserved word, so using "casing"
const CASE_UPPER = 1;
const CASE_LOWER = 0;
function array_change_key_case(/*[int]*/ casing) {
// In case const is not allowed/used
if (casing === "CASE_UPPER") casing = 1;
else if (casing === "CASE_LOWER") casing = 0;
else if (casing === undefined) {
casing = 0;
}
for (a in this) {
if (a !== "length" && a !== arguments.callee.name) {
var temparr = this[a];
delete(this[a]);
if (casing) {
this[a.toUpperCase()] = temparr;
}
else {
this[a.toLowerCase()] = temparr;
}
}
}
}
Object.prototype.array_change_key_case = array_change_key_case;
Example JavaScript Usage
var arr = {dOgYears:"7", hUmanYears:"1"};
arr.length = 2;
arr.array_change_key_case(CASE_UPPER);
for (abc in arr) {
print(abc);
print(arr[abc]);
}
Output
length
2
DOGYEARS
7
HUMANYEARS
1
array_change_key_case
function array_change_key_case(casing) { if (casing === "CASE_UPPER") { casing = 1; } if (casing === "CASE_LOWER") { casing = 0; } if (casing === undefined) { casing = 0; } for (a in this) { if (typeof this[a] === "string") { var temparr = this[a]; delete this[a]; if (casing) { this[a.toUpperCase()] = temparr; } else { this[a.toLowerCase()] = temparr; } } } }