RABL - Render collection as object with the ids as keys RABL - Render collection as object with the ids as keys json json

RABL - Render collection as object with the ids as keys


To choose hash-map rather than array is definitely better option if have control on API backend codebase. From BigO notation hash lookup happens with constant O(1) time, not O(n) as for array.

Primary key lookup from the database is the most performant way to query data. Primary key is usually short and always indexed. In case of big data set use pagination.

Let's assume there is no RABL (you can always instantiate pure Ruby classes in RABL DSL code) but just an array:

array = [{id: 1, name: "John"}, {id: 2, name: "Foo"}, {id: 3, name: "Bar"}]hash  = {}array.each{ |elem,i| hash[elem[:id].to_s] = elem }# {"1"=>{:id=>1, :name=>"John"}, "2"=>{:id=>2, :name=>"Foo"}, "3"=>{:id=>3, :name=>"Bar"}}

To pass the Ruby hash to Javascript on client you probably want to encode it appropriately:

# hash.to_json# {"1":{"id":1,"name":"John"},"2":{"id":2,"name":"Foo"},"3":{"id":3,"name":"Bar"}}

From Javascript you query hash by its key:

hash = {"1":{"id":1,"name":"John"},"2":{"id":2,"name":"Foo"},"3":{"id":3,"name":"Bar"}}hash[1]# Object { id=1,  name="John"}