Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the order of a JavaScript object? [closed]

My JavaScript object looks like this:

"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 change the order of the object dynamically.

After sorting, the object should look as follows:

"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 possible way to do this?

like image 979
gauti Avatar asked Nov 29 '12 03:11

gauti


1 Answers

To get and then change the order of an Object's enumeration, you need to manually define the order. This is normally done by adding the properties of the object to an Array.

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

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

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

Now the order will always be that of the order given by Object.keys, but there's no guarantee that the order will be what you want.

You can take that Array and reorder it using whatever ordering you need.

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

This sort will sort the keys by the nested key property of each object after numeric conversion.

like image 77
I Hate Lazy Avatar answered Sep 30 '22 09:09

I Hate Lazy