0
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 5 years have passed since last update.

連想配列のkeyとvalue、更にkey同士を繋げてStringで出力する

0
Last updated at Posted at 2021-05-20

最近はVue.jsをやっていますが、連想配列の扱いで毎回躓くので備忘録を込めての投稿です。
今回はペアのkeyとvalueは"="で、他のkey同士は"&"でつないでみます。

How to

const URL_QUERIES = {'title': 0, 'byline': 1}
const queries = Object.keys(URL_QUERIES).map(key => [key, URL_QUERIES[key]].join('=')).join('&')

console.log(queries)
// 出力:title=0&byline=1

05/20追記

上記の様なURLのオプションで扱う場合はURLSearchParamsという便利なものがあるそうです。
共有ありがとうございますm(_ _)m

const queries = new URLSearchParams({'title': 0, 'byline': 1}).toString()

console.log(queries) // title=0&byline=1

どういう時に使うか

例で示した通りですが、vimeoなどの動画投稿サイトでは、シェアする際にタイトル表示しなかったり、ボタン表示しなかったりとオプションがあるのですが、
それをURL内で記述する必要があります。なので、URLの連想配列にこのQueriesを保持しておけばオプションを選択・統一することができます。

何事も一発で書けると気持ちが良いですね。

参考

0
0
2

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
0
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?