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.

2
  • What are expected results? Commented May 28, 2016 at 22:31
  • Good question, i edited :) Commented May 29, 2016 at 11:54

3 Answers 3

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;
    }, {});
Sign up to request clarification or add additional context in comments.

1 Comment

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); }
1

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

Comments

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.