2012-02-22 33 views
5

我有一個對象。有沒有一種方法可以在所有鍵上運行Uppercase? 我在做什麼是試圖每個元素大寫在此對象我可以在對象上運行大寫方法嗎?

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

我還沒有得到上面的命令來爲我工作。我對此有點新,所以感謝任何幫助!

+0

你能告訴我確切的JSONObj值,你可以在那個地方得到,這樣我們就可以分開鍵和值 – 2012-02-22 18:30:50

+0

{「John Smith」:25,「Jane Doe」:46,「Ben Franklin」:32} – astuttle 2012-02-22 18:34:14

回答

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

使用此方法來創建一個對象使用不同的密鑰:

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

如果你想改變一個對象(修改實例),使用

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); 
+0

Don忘記刪除原來的物品。 – 2012-02-22 18:11:09

+0

不,這個方法會創建一個* new *對象。 – Bergi 2012-02-22 18:14:38

+0

哦,你說的沒錯。抱歉。 – 2012-02-22 18:29:28

相關問題