CorneeldH CorneeldH - 1 year ago 78
Javascript Question

ordering keys from Javascript object into array

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


"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) {
var test = root[key];
var list = Object.keys(test).sort(function(a,b){ return test[a]-test[b] })

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.

Answer Source

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;
    }, {});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download