Javascript key-value

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
Original solution
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]);
  }
}
pending…
Alternative solution
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++) {
  if (previousGroup != json[i].Group) {
    array.push({
      Group: json[i].Group
    });
    previousGroup = json[i].Group;
  }
  array[array.length - 1][json[i].Key] = json[i].Value;
}
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment