Creating object array from key-value pairs

JavaScript performance comparison

Test case created

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Alternative 1
var values = [
  {'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 map = {};
values.forEach(function(value) {
  map[value.Group] = map[value.Group] || {Group: value.Group};
  map[value.Group][value.Key] = value.Value;
});

var results = Object.keys(map).map(function(key) { return map[key]; });
 
pending…
Alternative 2
var values = [
  {'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 group, results = [];
for (var i = 0; i < values.length; ) {
  results.push({Group: group = values[i].Group});
  do {
    results[results.length - 1][values[i].Key] = values[i].Value;  
  } while (++i < values.length && values[i].Group == group);
}
 
pending…

You can edit these tests or add even more tests to this page by appending /edit to the URL.

Compare results of other browsers

0 comments

Add a comment