HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

JSON lookup by key

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
jsonlookupkey

Problem

I always did my lookup in JSON collection like that:

var data = [
    {
        "Key": "1111-1111-1111",
        "Email": "test@test.com"
    }
];

function getByKey(key) {
    var found = null;

    for (var i = 0; i < data.length; i++) {
        var element = data[i];

        if (element.Key == key) {
           found = element;
       } 
    }

    return found;
}


But I always wondered if there was a better / more optimal way of doing this.

Any suggestions?

Bonus question: any way of sorting a JSON collection? I found with .sort() and a compare function. Is that the best way?

Solution

Another way you can do it is to have the collection in an object, and use the primary identifier as key. This identifier is usually a unique identifier for that entity, like a user id.

This is way faster than iterating over an array in search for a match. As far as I remember, accessing via a key only takes one operation, O(1) while iterating through an array would depend on the length of the array. Worst case is that your match is at the tip of the array, thus O(n).

var data = {
  "1111-1111-1111" : {
    "Email": "test@test.com"
  }
};

//get by key
var key = "1111-1111-1111";
var oneOneOne = data[key];

oneOneOne.Email //test@test.com


This is only good when you try to get the set by the key. Otherwise, you'd have to resort to other arrangements for other retrievals.

As for sorting though, objects don't guarantee order, though browsers do sort them somehow. As far as I know, iterating through properties of an object in Firefox and Chrome yield different orders in the way they are arranged.

Code Snippets

var data = {
  "1111-1111-1111" : {
    "Email": "test@test.com"
  }
};

//get by key
var key = "1111-1111-1111";
var oneOneOne = data[key];

oneOneOne.Email //test@test.com

Context

StackExchange Code Review Q#25858, answer score: 8

Revisions (0)

No revisions yet.