How to reorder a javascript object?

My JavaScript object is as follows:

"ivrItems": { "50b5e7bec90a6f4e19000001": { "name": "sdf", "key": "555", "onSelect": "fsdfsdfsdf" }, "50b5e7c3c90a6f4e19000002": { "name": "dfgdf", "key": "666", "onSelect": "fdgdfgdf", "parentId": null }, "50b5e7c8c90a6f4e19000003": { "name": "dfdf", "key": "55", "onSelect": "dfdffffffffff", "parentId": null } } 

Now I want to dynamically reorder the object.

After sorting, the object should look like this:

 "ivrItems": { "50b5e7bec90a6f4e19000001": { "name": "sdf", "key": "555", "onSelect": "fsdfsdfsdf" }, "50b5e7c8c90a6f4e19000003": { "name": "dfdf", "key": "55", "onSelect": "dfdffffffffff", "parentId": null } "50b5e7c3c90a6f4e19000002": { "name": "dfgdf", "key": "666", "onSelect": "fdgdfgdf", "parentId": null } } 

Is there any way to do this?

+4
source share
4 answers

You must use an array. Object keys have no order

like this:

 { "ivrItems": [ { "id": "50b5e7bec90a6f4e19000001", "name": "sdf", "key": "555", "onSelect": "fsdfsdfsdf" }, { "id": "50b5e7c8c90a6f4e19000003", "name": "dfdf", "key": "55", "onSelect": "dfdffffffffff", "parentId": null }, { "id": "50b5e7c3c90a6f4e19000002", "name": "dfgdf", "key": "666", "onSelect": "fdgdfgdf", "parentId": null } ] } 
+2
source

To get and then change the order of the objects, you need to manually determine the order. This is usually done by adding the properties of the object to the array.

 var keys = Object.keys(data.ivrItems); 

Now you can iterate through the keys array and use the keys to access the members of your irvItems object.

 keys.forEach(function(key) { console.log(data.irvItems[key]); }); 

Now the order will always have the order specified by Object.keys , but there is no guarantee that the order will be what you want.

You can take this array and reorder it using whatever order you need.

 keys.sort(function(a, b) { return +data.irvItems[a].key - +data.irvItems[b].key; }); 

This type sorts keys by the nested key property of each object after a numerical conversion.

+3
source

Javascript objects are still unordered.
You cannot do this.

+2
source

You will probably have a hard time with cross-browser compatibility if you do this in a browser. But computers are mostly deterministic, so you could probably accomplish this reliably in a single javascript engine implementation. For example, in the Chrome REPL / console, you can get this order by simply ordering the addition of properties:

 var n = {} nb = 2 nc = 3 var m = {} mc = 3 mb = 2 JSON.stringify(n) > "{"b":2,"c":3}" JSON.stringify(m) > "{"c":3,"b":2}" 

So, you can restore your object by adding the keys in the order in which you want to find them later.

But other people are right, if you want a true, predictable order, you should use an array.

0
source

All Articles