从服务我收到一个带键值对的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" }
]
Run Code Online (Sandbox Code Playgroud)
我需要将其转换为以下对象数组:
[
{ Group : "A", Name : "John", Age : 30, City : "London" },
{ Group : "B", Name : "Hans", Age : 35, City : "Berlin" },
{ Group : "C", Name : "José", Age : 25, City : "Madrid" }
]
Run Code Online (Sandbox Code Playgroud)
每个组可以包含任意数量的键值对.
目前我有一个可行的解决方案,但我不知道它是否是最佳的:
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]);
}
}
Run Code Online (Sandbox Code Playgroud)
你可以在这里查看小提琴:http://jsbin.com/ozizom/1/
你有更好的解决方案吗?
假设JSON记录将始终按Group排序,这是另一种方法:
var 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" }
];
var array = [];
var previousGroup = null;
for(var i=0; i<json.length; i++) {
var group = json[i].Group;
if(previousGroup != group) {
array.push({Group: group});
previousGroup = group;
}
array[array.length-1][json[i].Key] = json[i].Value;
}
Run Code Online (Sandbox Code Playgroud)
这是一个有效的例子.