2

I have a JSON file (myfile.json) that looks like this:

{"3":["c","d"], "3.5":["j","k"], "1.5":["a","b"], "2.5":["x","y"] }

What I want to do open the file and sort it using d3.js file opening.

 d3.json('myfile.json',function(err,datafull){
    for (var myval in datafull) {
        console.log(myval);
    }
  });

Now if I do that, the console.log will print they key in unsorted manner. How can I sort the file?

This is different question, because it involves file parsing.

neversaint
  • 60,904
  • 137
  • 310
  • 477
  • 1
    Put each item into an array and then sort the array. Or use `Object.keys()` to get an array of the keys, sort *that* array, then use it to access the properties of the original object in sorted order. But you can't sort a (non-array) object. – nnnnnn Sep 16 '15 at 00:29
  • @nnnnnn: How do you put the file into the array? – neversaint Sep 16 '15 at 00:37

1 Answers1

2

To sort object keys you can use Object.keys() method which gives an array of the given objects keys then you can use the array sort() method.

d3.json('myfile.json',function(err,data){
  keys = Object.keys(data),
  i, len = keys.length;
  keys.sort(function(a, b) {
    return a - b;
  });

  for (i = 0; i < len; i++)
  {
    var a = keys[i];
    console.log(a + ':' + data[a]);
  }
}

See http://jsfiddle.net/sjmcpherso/mvrWb/234/

sjm
  • 5,378
  • 1
  • 26
  • 37