JSFiddle - React, Tailwind, and code Playground

by DakotaSv

HTML

<div id="content"></div>

JavaScript

var users = [{'Name' : 'John', 'Attributes' : {'Age' : 5, 'Height' : 1.5, 'Clothes' : {'Shirts' : 5, 'Pants' : 8}}}, {'Name' : 'Andrew', 'Attributes' : {'Age' : 9, 'Height' : 1.8, 'Clothes' : {'Shirts' : 2, 'Pants' : 5}}}, {'Name' : 'Lucifer', 'Attributes' : {'Age' : 11, 'Height' : 1.3, 'Clothes' : {'Shirts' : 9, 'Pants' : 4}}}];

users = users.sort(function (a, b) {
    return b["Attributes"]["Height"] - a["Attributes"]["Height"];
});

function output() {
    $("#content").clear;
    var text = "";
    $.each(users, function( key, value ) {
        text += "<div id='" + value["Name"] + "'>" + 
            "<span class='sort' id='" + value["Name"] + "-Name'><strong>" + value["Name"] + ":</strong></span> " +
            "<span class='sort' id='" + value["Name"] + "-Attributes-Age'>Age: " + value["Attributes"]["Age"] + "</span>, " +
            "<span class='sort' id='" + value["Name"] + "-Attributes-Height'>Height: " + value["Attributes"]["Height"] + "</span>, " + 
            "<span class='sort' id='" + value["Name"] + "-Attributes-Clothes-Shirt'>Shirts: " + value["Attributes"]["Clothes"]["Shirts"] + "</span>, " + 
            "<span class='sort' id='" + value["Name"] + "-Attributes-Clothes-Pants'>Pants: " + value["Attributes"]["Clothes"]["Pants"] + "<span></div><br>";
    });
    $("#content").html(text);
}
output();

//alert(eval("users[0][\"Name\"]"));

$(document).on("click", ".sort", function(){
    var sortId = this.id;
    var parts = sortId.split("-");
    
    var evaluation = "";
    for(i=1; i<parts.length; i++){
        evaluation += "[\"" + parts[i] + "\"]";
    }
    
    alert(evaluation);
    
    users = users.sort(function (a, b) {
        return eval("b" + evaluation) - eval("a" + evaluation);
        //return b["Attributes"]["Clothes"]["Shirts"] - a["Attributes"]["Clothes"]["Shirts"];
    });
    output();
});