Last active
April 24, 2020 14:01
-
-
Save plugn/8dc064696543fecb86201816a446dc0a to your computer and use it in GitHub Desktop.
Object deep sort by keys
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var sample = { | |
el: { | |
upload: 'Upload file', | |
filterPopover: { | |
apply: 'Apply' | |
}, | |
rightholdersItem: { | |
cardInterestedParty: 'Interested Party', | |
documents: 'Documents', | |
catalog: 'Catalogue' | |
}, | |
dialogReportsSearchForm: { | |
chooseReport: 'Choose report', | |
search: 'Search', | |
number: 'Number', | |
period: 'Period', | |
contragent: 'Contragent', | |
category: 'Category', | |
contract: 'Contract', | |
amount: 'Amount', | |
source: 'Source' | |
}, | |
}, | |
filter: { | |
filter: 'Filter', | |
discard: 'Reset', | |
apply: 'Apply' | |
} | |
} | |
// returns new object sorted by keys alphabetically | |
sortObject(sample) | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Sorts an Object by keys alphabetically | |
function collectValuesByPath(object, path=[]) { | |
let result = {} | |
const keys = Object.keys(object) | |
keys.forEach(key => { | |
let value = object[key] | |
const currentPath = path.concat(key) | |
if (typeof value === 'object' && value) { | |
const deeperValue = collectValuesByPath(value, currentPath) | |
result = {...result, ...deeperValue } | |
} else { | |
result = {...result, [currentPath.join('.')]: value} | |
} | |
}) | |
return result | |
} | |
function setNested(object={}, path=[], value) { | |
const keys = Array.isArray(path) ? path : path.split('.') | |
if (!keys.length) { | |
return object | |
} | |
const currentKey = keys[0] | |
if (keys.length === 1) { | |
object[currentKey] = value | |
} | |
else { | |
object[currentKey] = setNested(object[currentKey] || {}, keys.slice(1), value) | |
} | |
return object | |
} | |
function getSortedPaths(object) { | |
return Object.keys(collectValuesByPaths(sample)).sort() | |
} | |
function createSortedObject(valuesByPath, sortedPaths) { | |
let result = {} | |
sortedPaths.forEach(path => { | |
setNested(result, path, valuesByPath[path]) | |
}) | |
return result | |
} | |
function sortObject(object) { | |
const valuesByPath = collectValuesByPath(object) | |
const sortedPaths = getSortedPaths(valuesByPath) | |
return createSortedObject(valuesByPath, sortedPaths) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment