Files
reference/note/javascript/object/sort-an-object-by-its-properties.md
T
2022-10-18 11:37:51 +08:00

827 B

title, tags, layout
title tags layout
How to sort an object by its properties in JavaScript
JavaScript
ES6
one-line
js
Object
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',
}
*/