2

In JavaScript I have following code:

var rights = {
    'One': [ 1, 1, 0],
    'Two': [ 1, 0, 0],
    'Three': [ 0, 1, 1 ]
};

And printing:

for (item in rights) Response.Write(item + ' = ' + rights[item] + '<br />');

Also, I can access any element in object by this:

rights['One'] or rights[0]

But how can I iterate through this object makeing indexes lowercased so that it becomes as follows:

var rights = {
    'one': [ 1, 1, 0],
    'two': [ 1, 0, 0],
    'three': [ 0, 1, 1 ]
};

3 Answers 3

5

You can't directly change a key. You can get the key and its value, set a new key with lowercase key value and then remove the original key.

var rights = {
    'One': [ 1, 1, 0],
    'Two': [ 1, 0, 0],
    'Three': [ 0, 1, 1 ]
};

for (var key in rights) {
    var keyLower = key.toLowerCase();
    // if key is not already lower case
    if (keyLower !== key) {
        var temp = rights[key];
        delete rights[key];
        rights[keyLower] = temp;
    }
}

// all keys in the rights object will now be lowercase

Working demo: http://jsfiddle.net/jfriend00/U9vFQ/

Sign up to request clarification or add additional context in comments.

Comments

0
var fieldNames = [];
for (item in rights) { fieldNames.push(item); }
for(i = 0; i < fieldNames.length; i++) {
    var fieldName = fieldNames[i];
    var value = rights[fieldName];
    delete rights[fieldName];

    rights[fieldName.toLowerCase()] = value;    
}

1 Comment

Yeah, it's redundant, I just don't like the idea when you iterate through array and change it in the same time, it could be misleading. I have C# and a little Java background so it seems in js world it's fine :)
0
for (var key in rights) {

key = key.toLowerCase();

}

here is fiddle: http://jsfiddle.net/btevfik/JBAXr/


ok this doesn't actually update the key. just gives you the key in lowercase.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.