After receiving a JSON object with key-value pairs from a service, my task is to dynamically create objects based on them and group them by one column.
Here is an example of the JSON structure:
[
{ "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" }
]
The desired output should be an array of objects like this:
[
{ Group : "A", Name : "John", Age : 30, City : "London" },
{ Group : "B", Name : "Hans", Age : 35, City : "Berlin" },
{ Group : "C", Name : "José", Age : 25, City : "Madrid" }
]
There can be any number of key-value pairs within each group.
I currently have a functional solution for this task, but I am unsure if it is the most efficient approach:
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 = [];
// Creating a "hash" object to organize data
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;
}
// Adding each item in the hash to the results array
for (record in hash) {
if(hash.hasOwnProperty(record)) {
results.push(hash[record]);
}
}
You can view a demo here: http://jsbin.com/ozizom/1/
If you have a more optimal solution for this problem, please feel free to share.