mirror of
https://github.com/Fechin/reference.git
synced 2026-11-21 13:34:06 +03:00
827 B
827 B
title, tags, layout
| title | tags | layout | |||||
|---|---|---|---|---|---|---|---|
| How to sort an object by its properties in JavaScript |
|
note |
In this Article we will go through how to sort an object by its properties only using single line of code in JavaScript.
This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => Arrow Function.
Let's define this short function:
const sort = obj => Object.keys(obj).sort().reduce((p, c) => (p[c] = obj[c], p), {});
Example
const colors = {
white: '#ffffff',
black: '#000000',
red: '#ff0000',
green: '#008000',
blue: '#0000ff',
};
sort(colors);
/*
{
black: '#000000',
blue: '#0000ff',
green: '#008000',
red: '#ff0000',
white: '#ffffff',
}
*/