1

I saw this topic and the answers, but it doesn't seem to work for me. I tried alll variants of the values in the Object and sort, but it doesn't seem to work. I want to get a list ordered on the keys (not their values) in the objects (the, in this example 2 objects are in in a json):

d3.json:

{
"TEST1":    {"purchase": ["yes", 2], "safety": ["no", 3], "quality": ["Carried by the husk", 1], "name": ["Eggs!", 0]},
"TEST2":    {"purchase": "yes", "safety": "no", "quality": "Carried by the husk", "name": "0"}

}

And the JavaScript:

d3.json("d3.json", function(root) {

  for (key in root) {
      console.log(root[key]);
      var test = root[key];
      var list = Object.keys(test).sort(function(a,b){ return test[a]-test[b] })
      console.log(list);
  }
});

EDIT: Apologies, I wasn't clear on the expected results: I was looking for the keys sorted, but return with their values as the answer of dlopez did.

Community
  • 1
  • 1
CorneeldH
  • 593
  • 1
  • 8
  • 21

3 Answers3

2

Try with this:

var sortedByKeys = Object.keys(root)
    .sort(function(a,b) { return a - b; })
    .reduce(function(prev, curr) {
        prev[curr] = root[curr];
        return prev;
    }, {});
dlopez
  • 969
  • 5
  • 17
  • Thanks! Especially for interpreting the desired results :) In ended up needing an extra step (starting of with (for key in root), your code only sort the objects in the root, not the ones in root[key]) and I could leave out the sort-function (as stated by aromatt): for (key in root) { var sortedByKeys = Object.keys(root[key]) .sort() .reduce(function(prev, curr) { prev[curr] = root[key][curr]; return prev; }, {}); console.log(sortedByKeys); } – CorneeldH May 29 '16 at 11:53
1

By using test[a] - test[b] in the sort call back function, you sort by the property values, not the keys. To sort by the keys you can use this:

  var list = Object.keys(test).sort(function(a,b){ return a.localeCompare(b) })

which is the default sorting order, so:

  var list = Object.keys(test).sort()
trincot
  • 317,000
  • 35
  • 244
  • 286
1

You could simply use var list = Object.keys(test).sort();

aromatt
  • 66
  • 3