0

Sort object by key name alphabetically

Function JavaScript 1 revisions 139 a year ago a year ago
function sortObjectByKey(object) {
	const sortedObject = {};
	for (let keyName of Object.keys(object).sort()) {
		sortedObject[keyName] = object[keyName];
	}
	return sortedObject;
}

This function sorts an object by its key names. For example {b: 1, a: 2} would become {a: 2, b: 1}