0

I have a json object that looks something like:

{
    posts: [
        {id: 56, title: 'something', date: '10-10-10 00:00:00'},
        {id: 57, title: 'Apples', date: '10-10-16 00:00:00'},
    ]
}

And I am trying to learn how to manipulate data structures in Javascript. I would like to use jquery to reorder these based on the posts attributes, so you might reorder based on date, title or id (default is id).

How ever being a novice, I have no idea where to start I have seen this answer andI dont think its the direction I want to go.

Would the resulting out put be in the same structure? How could I create a collections of models based off this kind of "re-ordering".

The idea is to allow for editing and publishing of one model in a collection, based off the attribute used to re-order or "sort" the collection, thus allowing for faster processing - so I don't always have to pass the whole collection to the server when I really just want to update one model in the collection.

Community
  • 1
  • 1
user3379926
  • 3,855
  • 6
  • 24
  • 42
  • 3
    As the structure you want is an object with keys, it can't really be sorted as there is no order in objects. – adeneo Mar 19 '14 at 21:12
  • Updated the question to add more options for answers @adeneo – user3379926 Mar 19 '14 at 21:17
  • Do you want to just sort the `posts` array? See [this answer](http://stackoverflow.com/questions/1129216/sorting-objects-in-an-array-by-a-field-value-in-javascript). – Blazemonger Mar 19 '14 at 21:17
  • @Blazemonger No this would be a general thing where you pass in the "key" whos resulting value you wanted sorted and the second option would be "sort by what" - where it would check if that attribute exists before sorting. – user3379926 Mar 19 '14 at 21:19

1 Answers1

0

Take a look at the JavaScript array.sort method. It may do what you want.

var posts = [{"id": 57, "title": "something"}, {"id": 56, "title": "something else"}];
posts.sort(function(a, b) { if (a.id < b.id) { return -1; } else { return 1; } });
for (var i=0; i<posts.length-1; i++) {
    console.log(posts[i].title);
}
// prints "something else" followed by "something"

The sort method takes a function which is passed two elements, a and b, and you can return -1 if a is less than b, 0 if they are equal, and 1 if a is greater than b.

Note that my posts variable above is just a simplified version of what would be o.posts if your described JSON was stored at o. Also note that sort sorts in place, meaning it will change the array it operates over.

Two-Bit Alchemist
  • 17,966
  • 6
  • 47
  • 82