Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
4
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

@alucky0707

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

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

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 (数値にあまり意味は無い)

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

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
4
Help us understand the problem. What are the problem?