LoginSignup
0
0

More than 5 years have passed since last update.

inputのnameとvalueを取得してObjectのkeyとvalueにする

Last updated at Posted at 2018-10-02

表題のとおり、下記のHTMLのソースから

<div id="hoge" style="display:none;">
  <input type="hidden" name="fuga1" value="piyo1">
  <input type="hidden" name="fuga2" value="piyo2">
  <input type="hidden" name="fuga1" value="piyo3">
</div>

このように「name」を「key」に「value」を「value」にする書き方です。

obj {
  fuga1: piyo1,
  fuga2: piyo2,
  fuga3: piyo3
}

書き方

const inputTags = document.querySelectorAll('#hoge input');
const list = Array.from(inputTags).map(obj => ({[obj.name]: obj.value}))
const obj = Object.assign({}, ...list);
console.log(obj)

ちなみにBabelで変換しないとArray.fromはIEサポートしてないです。

0
0
0

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