Help us understand the problem. What is going on with this article?

Objectのkeyとvalueを反転させる。もしくはJSでenum的なものを作る。

More than 5 years have passed since last update.

久しぶりに本当にメモ。最近あまりによく使うので。

inverse.js
/**
 * オブジェクトのkeyとvalueを反転させる
 * @param {Object} obj 反転させるオブジェクト
 * @param {Boolean} [keyIsNumber=false] keyが数値であるか?(数値ならkeyを反転させるとき数値に変換する)
 * @return {Object} keyとvalueの反転したオブジェクト
 */
function inverseObject (obj, keyIsNumber) {
  return Object.keys(obj).reduceRight(function (ret, k) {
    return (ret[obj[k]] = keyIsNumber ? parseInt(k, 10) : k, ret);
  }, {});
}

使い方はこんな感じ。

inverse_usage.js
var
obj = {
  foo: 'bar',
  bar: 'foo',
},
inv = inverseObject(obj); //=> {bar: 'foo', foo: 'bar'}

// あんましこういう使い方しない…
console.log(obj[inv[obj[inv.foo]]])

var
// こんな風にしてenum的なものを作る
enumKeys = 'aaa bbb ccc'.split(' '),
enumLike = inverseObject(enumKeys);

console.log(enumLike.aaa); //=> 0 (数値にあまり意味は無い)

ちょっと使い方の説明が微妙な感じだけどこれでっ

alucky0707
ウィルキンソンジンジャエールを片手にコードを書く人。JavaScriptぐらいしかまともに書けない…。東京都内の工業高校に通うザコ学生。
http://alucky0707.hatenablog.com/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした