Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I run an uppercase method on an object?

I have an object. Is there a way to run toUppercase on all of its keys? What I'm doing is trying to uppercase every element in this object

JSON.stringify(JSONObj.people).toUpperCase()

I haven't gotten the above command to work for me. I'm a bit new to this, so appreciate any help!

like image 668
astuttle Avatar asked Feb 22 '12 17:02

astuttle


1 Answers

Object.withUpperCaseKeys = function upperCaseKeys(o) {
// this solution ignores inherited properties
    var r = {};
    for (var p in o)
        r[p.toUpperCase()] = o[p];
    return r;
}

Use this method to create a new object with different keys:

JSONObj.people = Object.withUpperCaseKeys(JSONObj.people);

If you want to change an object (modify the instance), use

Object.upperCaseKeys = function upperCaseKeys(o) {
// this solution ignores inherited properties
    for (var p in o)
        if (p.toUpperCase() != p) {
            o[p.toUpperCase()] = o[p];
            delete o[p];
        }
    return o; // just for easier chaining
}

Object.upperCaseKeys(JSONObj.people);
like image 152
Bergi Avatar answered Nov 13 '22 00:11

Bergi