Method 1: ES3
function sort_obj_by_values(obj) { var sortable = []; for (var i in obj) { sortable.push([i, obj[i]]); } sortable.sort(function(a, b) { return a[1] - b[1]; }); var objSorted = {} sortable.forEach(function(item) { objSorted[item[0]] = item[1] }) return objSorted } var obj = { a: 300, c: 60, b: 200, f: 1000, d: 400, e: 8 * 60 * 60 }; console.log(JSON.stringify(sort_obj_by_values(obj))) //{"c":60,"b":200,"a":300,"d":400,"f":1000,"e":28800}
Method 2: ES6
function sort_obj_by_values(obj) { return Object.keys(obj). sort(function(a,b){return obj[a]-obj[b]}). reduce((r, v) => ({ ...r, [v]: obj[v] }), {}); }
Method 3: ES8, use Object.entries() to convert the object into an array
function sort_obj_by_values(obj) { return Object.entries(obj) .sort(([,a],[,b]) => a-b) .reduce((r, [k, v]) => ({ ...r, [k]: v }), {}); }
Method 4: ES10, use Object.fromEntries() to convert array to object
function sort_obj_by_values(obj) { return Object.fromEntries( Object.entries(obj).sort(([,a],[,b]) => a-b) ) }
Method 5: TypeScript ES2019
/** * Represents an associative array of a same type. */ interface Dictionary<T> { [key: string]: T; } /** * Sorts an object (dictionary) by value or property of value and returns * the sorted result as a Map object to preserve the sort order. */ function sort<TValue>( obj: Dictionary<TValue>, valSelector: (val: TValue) => number | string, ) { const sortedEntries = Object.entries(obj) .sort((a, b) => valSelector(a[1]) > valSelector(b[1]) ? 1 : valSelector(a[1]) < valSelector(b[1]) ? -1 : 0); return Object.fromEntries(sortedEntries); }
Usage:
var list = { "one": { height: 100, weight: 15 }, "two": { height: 75, weight: 12 }, "three": { height: 116, weight: 9 }, "four": { height: 15, weight: 10 }, }; var sortedObj = sort(list, val => val.height); console.log(sortedObj)
Result:
{ "four": { "height": 15, "weight": 10 }, "two": { "height": 75, "weight": 12 }, "one": { "height": 100, "weight": 15 }, "three": { "height": 116, "weight": 9 } }