從服務中,我收到一個帶有鍵值對的JSON對象,我需要從它們動態地創建對象,按一列分組。從鍵值對創建對象數組
的JSON看起來像這樣:
[
{ "Group" : "A", "Key" : "Name", "Value" : "John" },
{ "Group" : "A", "Key" : "Age", "Value" : "30" },
{ "Group" : "A", "Key" : "City", "Value" : "London" },
{ "Group" : "B", "Key" : "Name", "Value" : "Hans" },
{ "Group" : "B", "Key" : "Age", "Value" : "35" },
{ "Group" : "B", "Key" : "City", "Value" : "Berlin" },
{ "Group" : "C", "Key" : "Name", "Value" : "José" },
{ "Group" : "C", "Key" : "Age", "Value" : "25" },
{ "Group" : "C", "Key" : "City", "Value" : "Madrid" }
]
我需要將其轉換到以下對象數組:
[
{ Group : "A", Name : "John", Age : 30, City : "London" },
{ Group : "B", Name : "Hans", Age : 35, City : "Berlin" },
{ Group : "C", Name : "José", Age : 25, City : "Madrid" }
]
每個組可以包含任意數量的鍵 - 值對。
目前我對這個工作的解決方案,但我不知道這是否是最佳的:
var items = [
{ "Group" : "A", "Key" : "Name", "Value" : "John" },
{ "Group" : "A", "Key" : "Age", "Value" : "30" },
{ "Group" : "A", "Key" : "City", "Value" : "London" },
{ "Group" : "B", "Key" : "Name", "Value" : "Hans" },
{ "Group" : "B", "Key" : "Age", "Value" : "35" },
{ "Group" : "B", "Key" : "City", "Value" : "Berlin" },
{ "Group" : "C", "Key" : "Name", "Value" : "José" },
{ "Group" : "C", "Key" : "Age", "Value" : "25" },
{ "Group" : "C", "Key" : "City", "Value" : "Madrid" }
], item, record, hash = {}, results = [];
// Create a "hash" object to build up
for (var i = 0, len = items.length; i < len; i += 1) {
item = items[i];
if (!hash[item.Group]) {
hash[item.Group] = {
Group : item.Group
};
}
hash[item.Group][item.Key] = item.Value;
}
// Push each item in the hash to the array
for (record in hash) {
if(hash.hasOwnProperty(record)) {
results.push(hash[record]);
}
}
您可以檢查這裏的小提琴:http://jsbin.com/ozizom/1/
你對此有一個更好的解決方案?
按照你的例子,JSON是否總是按Group排序? – sp00m
是的,JSON字段組,鍵和值給出,並且記錄總是按組排序 – tpolyak