简体   繁体   中英

accessing and sorting array objects in json using javascript

I'm playing around with json objects in javascript and wanted see if someone could help me out with a problem

My json file contains a list of hash objects containing a key (id) and the value being an array of [ ipaddress, timestamp, url]

eg

{"output":
    {
    "1":["10.0.0.1","2012-07-11T11:41:42+01:00","http://myurl.com"],
    "2":["10.0.0.1","2012-07-11T11:45:42+01:00","http://myurl2.com"],
    "3":["192.168.1.1","2012-07-11T11:41:47+01:00","http://myurl3.com"]
    }
}

What I want to do is be able to sort on the contents of the arrays

For example I'd like to go through the json and pull out the highest timestamp for each ip address

So an example output for the json above would look like:-

10.0.0.1 - http://myurl2.com
192.168.1.1 - http://myurl3.com

At the moment I have a simple function to output the raw data in a div, but I'm sure I could handle the arrays better

  var displayOutput = function(data){
    var container = $("#fragment-1");
   var body = “”;
    $.each(data.output, function(key, val) {
      var arr = val.toString().split(",");
      body = body + arr[0]+ ' - ' +  arr[1]) + ' - ' +  arr[2]
    });
    container.html(body);                                                
  };

You will need to change the format as JSON arent to easy to sort.

Maybe a multi dimensional array?

Maybe this might help: Sorting an array of JavaScript objects

Or this: http://www.devcurry.com/2010/05/sorting-json-array.html

Or this: Sorting a JSON object in Javascript

One of these will definitely lead to to a good solution. Need any help ask :)

You can Use underscore.js library. For example, you can sort collection with:

_.sortBy(yourData.output, function (elem) {
    return new Date(elem[1]).getTime() - new Date().getTime();
});

Of course you need to parse JSON to JavaScript object first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM