2016-11-25 71 views
0

我有一個輸出象下面這樣:如何在JSON對象的鍵刪除空間

output = { 
    "New Classroom": [{ 
    "Name": "Apple", 
    "Age": "6", 
    "Percentage": "24.00%" 
    }, { 
    "Name": "Orange", 
    "Age": "5", 
    "Percentage": "9.88%" 
    }, { 
    "Name": "Green", 
    "Age": "2", 
    "Percentage": "27.27%" 
    }, { 
    "Name": "Grey", 
    "Age": "6", 
    "Percentage": "12.63%" 
    }] 
} 

如何與NewClassroom取代New Classroom和新教室並不總是一個「NewClassroom」。它可能是不同的文字

ob = JSON.parse(output); 

alert(Object.keys(ob)) 

我這樣做的時候,我得到Newclassroom爲重點

回答

2

您可以通過對象的頂級屬性名稱循環您RECE如果有空格,請檢查任何空格,並刪除空格。 (你不需要,他們是完全有效的屬性名稱,但你可以如果你想。)

var output = { "New Classroom": [{"Name": "Apple","Age": "6","Percentage": "24.00%"},{"Name": "Orange","Age": "5","Percentage": "9.88%"},{"Name": "Green","Age": "2","Percentage": "27.27%"},{"Name": "Grey","Age": "6","Percentage": "12.63%"}]}; 
 
var name, newName; 
 
// Loop through the property names 
 
for (var name in output) { 
 
    // Get the name without spaces 
 
    newName = name.replace(/ /g, ""); 
 
    // If that's different... 
 
    if (newName != name) { 
 
    // Create the new property 
 
    output[newName] = output[name]; 
 
    // Delete the old one 
 
    delete output[name]; 
 
    } 
 
} 
 
console.log(output);

注意,在對象上使用delete可以降低性能後續的財產查詢。 99.99%的時間,沒關係。如果你的情況的問題,創建一個對象,而不是在地方修改它:

var output = { "New Classroom": [{"Name": "Apple","Age": "6","Percentage": "24.00%"},{"Name": "Orange","Age": "5","Percentage": "9.88%"},{"Name": "Green","Age": "2","Percentage": "27.27%"},{"Name": "Grey","Age": "6","Percentage": "12.63%"}]}; 
 
var name, newName; 
 
var newOutput = {}; 
 
// Loop through the property names 
 
for (var name in output) { 
 
    // Get the name without spaces 
 
    newName = name.replace(/ /g, ""); 
 
    
 
    // Copy the property over 
 
    newOutput[newName] = output[name]; 
 
} 
 
console.log(newOutput);

+0

所以如果'Percentage'已經得到了一些空間,這將不起作用? – Mahi

+0

@馬希:我的印象不是問題。不,它不會,因爲我們只處理頂層對象。當然,可以將相同的主體應用於從屬數組中的對象... –

1
  • 使用Object.keys獲取對象
  • 使用String#replace到的所有鍵替換字符String

var obj = { 
 
    "New Classroom": [{ 
 
    "Name": "Apple", 
 
    "Age": "6", 
 
    "Percentage": "24.00%" 
 
    }, { 
 
    "Name": "Orange", 
 
    "Age": "5", 
 
    "Percentage": "9.88%" 
 
    }, { 
 
    "Name": "Green", 
 
    "Age": "2", 
 
    "Percentage": "27.27%" 
 
    }, { 
 
    "Name": "Grey", 
 
    "Age": "6", 
 
    "Percentage": "12.63%" 
 
    }] 
 
}; 
 

 
Object.keys(obj).forEach(function(key) { 
 
    var replaced = key.replace(' ', ''); 
 
    if (key !== replaced) { 
 
    obj[replaced] = obj[key]; 
 
    delete obj[key]; 
 
    } 
 
}); 
 
console.log(obj);

注:的空間只有單一的出現被認爲,RegEx可如果space發生是不止一次被使用!

+1

使用正則表達式進行替換,否則它只會替換第一個空格。 – MrCode

1

循環在json的每個鍵中,然後解析。

嘗試正則表達式

var word = "New Classroom" 
 
word = word.replace(/\s/g, ''); 
 
console.log(word)