1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

連想配列(オブジェクト)のキーと値を入れ替える。【javascript】

Last updated at Posted at 2022-02-25

解決に時間がかかったためメモ。

連想配列のキーを値に、値をキーにしたかった

const obj = {
  a : 'aaa',
  b : 'bbb',
  c : 'ccc'
}

これを

const obj = {
  aaa : 'a',
  bbb : 'b',
  ccc : 'c'
}

こうしたい

Object.entries, Object.fromEntries を使う

const array = Object.fromEntries(
  Object.entries(tmp).map(function (value) {
    return [value[1], value[0]];
  })
);
console.log(array);
array => {
  aaa : 'a',
  bbb : 'b',
  ccc : 'c'
}

できた。
Object.fromEntries が ES2019 から追加されたとのこと。

参考

https://qiita.com/c-shiraga/items/33812799e4dc17d89b44

1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?