1

i need help for sorting dataSource with JavaScript. My javascript code is mentioned below which is generating an unordered-list. If i click on "Generate Sorted list" it will be generating the output as follows:


Pen
  Cello
    C1
    C2
  Parker
    P1
    P2

Fiddle

var dataSource = ({
    "Pen": ({
        "Parker": ({
            "P1": ({}),
                "P2": ({})
        }),
            "Cello": ({
            "C2": ({}),
                "C1": ({})
        })
    })
}),
    traverseObject = function (obj) {
        var ul = document.createElement("ul"),
            li;

        for (var prop in obj) {
            li = document.createElement("li");
            li.appendChild(document.createTextNode(prop));
            li.onclick = function(e) {
                var classNames = e.currentTarget.className;
                if (classNames.indexOf("hidden") == -1) {
                    e.currentTarget.className += "hidden";
                } else {
                    e.currentTarget.className = e.currentTarget.className.replace("hidden", "");
                }
                e.stopPropagation();
            }

            if (typeof obj[prop] == "object" && Object.keys(obj[prop]).length) {
                li.appendChild(traverseObject(obj[prop]));
            } else {
                li.className += "leaf";
            }
            ul.appendChild(li);
            console.log(ul);
        }
        return ul;
    };


window.onload = function () {

   document.getElementById("dvList1").appendChild(traverseObject(dataSource));
  //  document.getElementById("hlGSL").onclick = function(){document.getElementById("dvList1").appendChild(sortedObject(dataSource));}
}
  • possible duplicate of [Iterate over a Javascript associative array in sorted order](http://stackoverflow.com/questions/890807/iterate-over-a-javascript-associative-array-in-sorted-order) – Cerbrus Feb 03 '14 at 10:40
  • can you please provide me a live fiddle, as i am confused for getting it sorted – user3237973 Feb 03 '14 at 10:42

2 Answers2

0

Traverse over the sorted key array instead of the object

http://jsfiddle.net/Ek2xS/36/

var keys = Object.keys(obj).sort();
for (prop in keys) {
    if (keys.hasOwnProperty(prop)) {
        li = document.createElement("li");
        li.appendChild(document.createTextNode(keys[prop]));


        if (typeof obj[keys[prop]] == "object" && Object.keys(obj[keys[prop]]).length) {
            li.appendChild(traverseObject(obj[keys[prop]]));
        } else {
            li.className += "leaf";
        }
        ul.appendChild(li);
        console.log(ul);
    }
}
Michal Brašna
  • 2,293
  • 13
  • 17
Ankur
  • 791
  • 4
  • 15
  • for in is meant to enumerate object properties http://stackoverflow.com/questions/3010840/loop-through-array-in-javascript – Michal Brašna Feb 03 '14 at 10:53
  • here we are enumerating the object properties, the only difference is that they now reside in a sorted array, which makes it easier to get the list/items displayed in the alphabetical order. Finally inside for in, I'm not traversing over keys, but using obj[keys[prop]] to get the values and nodes. – Ankur Feb 03 '14 at 10:55
  • You are right, that you traverse object properties. That object is an Array, so keys are 0, 1, 2 and possibly whatever was added to Array's prototype chain, which is really not a good idea. Try Array.prototype.foo = 5 and you have a problem. – Michal Brašna Feb 03 '14 at 11:03
  • Please help me to fix this bug. when i click on "Generate Sorted list", the list generates and then vanishes fiddle :http://jsfiddle.net/aliparvez20/Ek2xS/37/ – user3237973 Feb 03 '14 at 11:32
0

You could replace iteration over keys of object in undefined order

...
for (var prop in obj) {
...

with iterating over sorted keys

...
var sortedKeys = Object.keys(obj).sort();
for (var i = 0; i < sortedKeys.length; ++i) {
    var prop = sortedKeys[i];
...
Michal Brašna
  • 2,293
  • 13
  • 17