How to save an ordered Javascript object / array while also saving key search queries?

I have some data that I originally saved in a shared Javascript object, with an identifier as a key:

{ "7": {"id":"7","name":"Hello"}, "3": {"id":"3","name":"World"}, ... } 

However, I found that browsers do not guarantee a specific order of objects when passing through them, so in the above โ€œ3โ€ will appear before โ€œ7โ€. I switched to using an array format as follows:

 [ {"id":"7","name":"Hello"}, {"id":"3","name":"World"}, ... ] 

Now I can execute the loop in the correct order, but I can not do a quick search, for example. data["3"] without having to iterate over the array.

Is there a good way to combine both approaches? I would prefer not to use a separate object for each format, because the object is quite large (hundreds of elements).

+44
javascript data-structures
Apr 24 '11 at 23:32
source share
1 answer

I ran into this problem. The solution is to keep an ordered array of keys in addition to the original object.

 var objects = { "7": {"id":"7","name":"Hello"}, "3": {"id":"3","name":"World"}, ... } var order = [ "3", "7", ... ]; 

Now, if you need a second element, you can do this search:

 var second_object = objects[order[1]]; 

The ECMA standard does not say anything about the order of elements in an object. And especially Chrome reorders keys when they look like numbers. Example:

 var example = { "a": "a", "b": "b", "1": "1", "2": "2" }; 

if you print this in Chrome you will get something like:

 { 1: "1", 2: "2", "a": "a", "b": "b" }; 

It's a little sour .. but life.

You can use the Andy solution bundled as well, basically wrapping the two together in one object.

An alternative that I use a lot is a custom map function that allows you to specify the order in which an object moves. Typically, you will sort when you print your data to the user, so when you loop and create your table rows (for example), your iterator will pass the rows in the order that your sort function calls. I thought it was a good idea :)

The signature looks like this:

 function map(object, callback, sort_function); 

Usage example:

 map(object, function (row) { table.add_row(row.header, row.value); }, function (key1, key2) { return object[key1] - object[key2]; }); 
+60
Apr 24 2018-11-11T00:
source share



All Articles