Created
November 29, 2017 07:52
-
-
Save liesislukas/ccbc7fd885d315c2f938df95bb78013e to your computer and use it in GitHub Desktop.
orderObjectFields
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
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