CorneeldH CorneeldH - 6 months ago 31
JSON Question

ordering keys from Javascript object

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.

Answer

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;
    }, {});
Comments