Skip to content

Instantly share code, notes, and snippets.

@liesislukas
Created November 29, 2017 07:52
Show Gist options
  • Save liesislukas/ccbc7fd885d315c2f938df95bb78013e to your computer and use it in GitHub Desktop.
Save liesislukas/ccbc7fd885d315c2f938df95bb78013e to your computer and use it in GitHub Desktop.
orderObjectFields
const _ = require('lodash');
function orderObjectFields(input) {
if (!input) {
return input;
}
if (_.isString(input)) {
return input;
} else if (_.isArray(input)) {
let tmp = [];
input.forEach((item) => {
item = orderObjectFields(item);
tmp.push(item);
});
return tmp;
} else if (_.isObject(input)) {
let tmp = {};
let tmpKeys = Object.keys(input);
tmpKeys = tmpKeys.sort(); // abc....
tmpKeys = tmpKeys.sort((a, b) => { // _id fields first
if (a.slice(-3) === '_id' && b.slice(-3) !== '_id') {
return -1;
}
if (a.slice(-3) !== '_id' && b.slice(-3) === '_id') {
return 1;
}
return 0;
});
tmpKeys = tmpKeys.sort((a, b) => { // _at fields last
if (a.slice(-3) === '_at' && b.slice(-3) !== '_at') {
return 1;
}
if (a.slice(-3) !== '_at' && b.slice(-3) === '_at') {
return -1;
}
return 0;
});
tmpKeys.forEach((key) => {
tmp[key] = input[key];
});
return tmp;
}
return input;
}
module.exports = orderObjectFields;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment