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}}}
];
function output(list) {
$("#content").clear;
var text = "";
$.each(list, 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-Shirts'>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);
}
function sort(path, array){
return array.sort((a, b) => {
return getValue(b,path) - getValue(a,path)
});
function getValue(obj, path){
path.forEach(path => obj = obj[path])
console.log(obj);
return obj;
}
}
output(users);
$(document).on("click", ".sort", function(){
var sortId = this.id;
var parts = sortId.split("-");
parts.shift();
output(sort(parts, users));
});