Once you have the array, you can reconstruct the objects from the array in any order you like, achieving exactly what you want to do. This works in all browsers I'm aware of, but it depends on implementation quirks and may break at any time. You should never make assumptions about the order of elements in a JavaScript object.
let objSorted = {} sortable.forEach(function(item){ objSorted[item[0]]=item[1] })
In ES8, you can useObject.entries()to convert an object to an array:
We don't want to copy the entire data structure, or use an array where an associative array is required.
Here's another way to do the same thing as bonna:
var list = {"you": 100, "me": 75, "foo": 116, "bar": 15}; keysSorted = Object.keys(list).sort(function(a,b){return list[a]-list[b]}) console.log(keysSorted); // bar,me,you,fooMove them into an array, sort the array, and use that array for your purposes. The solution is as follows:
let maxSpeed = { car: 300, bike: 60, motorbike: 200, airplane: 1000, helicopter: 400, rocket: 8 * 60 * 60 }; let sortable = []; for (var vehicle in maxSpeed) { sortable.push([vehicle, maxSpeed[vehicle]]); } sortable.sort(function(a, b) { return a[1] - b[1]; }); // [["bike", 60], ["motorbike", 200], ["car", 300], // ["helicopter", 400], ["airplane", 1000], ["rocket", 28800]]Once you have the array, you can reconstruct the objects from the array in any order you like, achieving exactly what you want to do. This works in all browsers I'm aware of, but it depends on implementation quirks and may break at any time. You should never make assumptions about the order of elements in a JavaScript object.
let objSorted = {} sortable.forEach(function(item){ objSorted[item[0]]=item[1] })In ES8, you can use
Object.entries()to convert an object to an array: