If I have this JS object literal:
var foo = {
Sussy: 4,
Billy: 5,
Jimmy: 2,
Sally: 1
};
How can I create a new, sorted object literal:
var bar = {
Sally: 1,
Jimmy: 2,
Sussy: 4,
Billy: 5
};
Arrays of objects can be sorted by comparing the value of one of their properties.
To sort the keys of an object:Use the Object. keys() method to get an array of the object's keys. Call the sort() method on the array. Call the reduce() method to get an object with sorted keys.
Object Literal. In plain English, an object literal is a comma-separated list of name-value pairs inside of curly braces. Those values can be properties and functions.
There are two methods to iterate over an object which are discussed below: Method 1: Using for…in loop: The properties of the object can be iterated over using a for..in loop. This loop is used to iterate over all non-Symbol iterable properties of an object.
Turns out object property order is predictable since ES2015. Which is amazing.
Check it out here.
Re: How to sort a JS Object?
Answer: You can't. So instead, you need a more sophisticated data structure. You have many options:
I recommend solution 3 since it uses the JS mechanics to manage the ordering.
Examples:
// Object holds sort order: (Solution 2)
var foo = {
Suzy: {v: 4, order: 0},
Billy: {v: 5, order: 1},
Jimmy: {v: 2, order: 2},
Sally: {v: 1, order: 3}
};
// Array holds keys: (Solution 3)
var woof = [
{k: 'Suzy', v: 4},
{k: 'Billy', v: 5},
{k: 'Jimmy', v: 2},
{k: 'Sally', v: 1}
];
// Sort the woof array by the key names:
woof.sort(function(a, b) {
return a.k.localeCompare(b.k);
});
// The third key and value:
woof[2].k; // the third key
woof[2].v; // the third value
Edited: updated code to fix typo. Thank you, @Martin Fido
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With