Can I run an uppercase method on an object?

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

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

I did not get the above command to work for me. I'm a little new to this, so appreciate any help!

+5
source share
1 answer
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 the object (change the instance), use

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

Object.upperCaseKeys(JSONObj.people);
+6
source

All Articles