For example the following
var data = {
\'States\': [\'NSW\', \'VIC\'],
\'Countries\': [\'GBR\', \'AUS\'],
\'Capitals\': [\'SYD\', \'MEL\']
}
for
I would add this as a comment to @prototype's post, but my rep isn't high enough.
If anyone needs a version of orderKeys that @prototype wrote that is compliant with eslint-config-airbnb:
/**
* Returns and modifies the input object so that its keys are returned in sorted
* order when `Object.keys(obj)` is invoked
*
* @param {object} obj The object to have its keys sorted
*
* @returns {object} The inputted object with its keys in sorted order
*/
const orderKeys = (obj) => {
// Complying with `no-param-reassign`, and JavaScript seems to assign by reference here
const newObj = obj;
// Default `.sort()` chained method seems to work for me
const keys = Object.keys(newObj).sort();
const after = {};
// Add keys to `after` in sorted order of `obj`'s keys
keys.forEach((key) => {
after[key] = newObj[key];
delete newObj[key];
});
// Add keys back to `obj` in sorted order
keys.forEach((key) => {
newObj[key] = after[key];
});
return newObj;
};
Using @prototype's tests:
const example = {
3: 'charlie',
'p:style': 'c',
berries: 'e',
'p:nvSpPr': 'a',
'p:txBody': 'd',
apples: 'e',
5: 'eagle',
p:spPr: 'b'
}
const obj = orderKeys(example);
console.log(obj);
console.log(Object.keys(obj));
Outputs the following:
Babel Compiler v6.4.4
Copyright (c) 2014-2015 Sebastian McKenzie
{ 3: 'charlie',
5: 'eagle',
apples: 'e',
berries: 'e',
'p:nvSpPr': 'a',
'p:spPr': 'b',
'p:style': 'c',
'p:txBody': 'd' }
[ '3',
'5',
'apples',
'berries',
'p:nvSpPr',
'p:spPr',
'p:style',
'p:txBody' ]
For whatever it's worth, I needed this in my React app so that I could sort the options of a dropdown that was based on a state object, assigned after a response from my API.
Initially I did
return (
// ...
// ...
);
But realized the .sort() method would be invoked on each re-render, hence needing @prototype's implementation of orderKeys.
https://stackoverflow.com/users/645715/prototype