Last active
January 29, 2020 00:27
-
-
Save discoNeko/bc0092c5af8a70b05a7d46da79902260 to your computer and use it in GitHub Desktop.
順番の乱れたobjectをkeyでsortする.js
This file contains 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
// 順番の乱れたobjectをkeyでsortする | |
const object1 = { | |
a: 'somestring', | |
c: false, | |
b: 42 | |
}; | |
console.log(Object.keys(object1)); | |
// expected output: Array ["a", "c", "b"] | |
// これをa,b,cの順で処理したい | |
// ObjectをArrayに変換して標準関数でsortする | |
console.log(Object.keys(object1).sort()) | |
// expected output: Array ["a", "b", "c"] | |
// ObjectをArrayに変換して標準関数でsortしてからfilterで順次処理を回す | |
Object.keys(object1).sort().filter(key => console.log('key[' + key + '] val : ' + object1[key])) | |
// expected output: | |
// "key[a] val : somestring" | |
// "key[b] val : 42" | |
// "key[c] val : false" | |
// sortしたあと再度Objectに戻す | |
const rebuildObject = Object.keys(object1).sort().reduce((object, key) => { | |
object[key] = object1[key] | |
return object | |
}, {}) | |
console.log(rebuildObject) | |
// expected output: Object { a: "somestring", b: 42, c: false } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment