1

I want to map a list of categories from a desktop site to the matching mobile categories. It's need to be done on client with JavaScript on every page, so it should be quiet fast.

So i started with this:

var mapDesktop2Mobile = [{"news":"panorama"}, {"local":"someothercat"}];

now i want to get returned "panorama", if my desktop category is "news".

How can i get value?

kidata
  • 165
  • 1
  • 2
  • 15
  • possible duplicate of [Access / process (nested) objects, arrays or JSON](http://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) – Felix Kling Mar 07 '14 at 17:27
  • 2
    Although it would make more sense to just create a single object instead of an array of objects. Then you can access the property directly, now you have to iterate over the array first. – Felix Kling Mar 07 '14 at 17:28
  • 1
    P.S. That's not JSON. It's a JavaScript array. – gen_Eric Mar 07 '14 at 17:29

2 Answers2

4

To be fast you shouldn't nest the object (which acts as a dictionary) in an array, but just use an object:

var mapDesktop2Mobile = {"news":"panorama", "local":"someothercat"};

At that point you can get the value with:

mapDesktop2Mobile["news"]

If you need a dictionary of more complex objects you can use the value of a UNIQUE property as the key, much like this:

var complexDictionary = {
    "key01" : { "name" : "key01", "property1" : 1, "property2" : 4 },
    "key02" : { "name" : "key02", "property1" : 2, "property2" : 3 },
    "key03" : { "name" : "key03", "property1" : 3, "property2" : 2 },
    "key40" : { "name" : "key40", "property1" : 4, "property2" : 1 }
};

The fact that you repeat the property as a key should be of no concern, you won't allocate much more memory and leverage the full speed of the VM implementation (mostly with hashes, buckets and native platform code -- you can't hope to get any faster than that).

pid
  • 11,472
  • 6
  • 34
  • 63
2

Why are you using an array for your map? Don't. Use an object with multiple properties.

var mapDesktop2Mobile = {
    "news":"panorama",
    "local":"someothercat"
};

Then you can simply do mapDesktop2Mobile.news (or mapDesktop2Mobile['news']).

gen_Eric
  • 223,194
  • 41
  • 299
  • 337