首页 > 解决方案 > 如何遍历所有属性并将值作为对象返回

问题描述

我需要编写一个函数,该函数接受一个参数列表,该参数是一个元素列表。元素都是labelsinputs。函数应该创建一个对象,其中的文本是labels对象的键,而值是inputs属于对象键的值。我需要我的函数必须返回这个对象。

let elements = document.querySelectorAll('form *') //Selects all children of the form element
formObj(elements)

//I need it to return: {name: "Harry, email: "harry@gmail.com", age: 22}
<form>
    <label for='name'>name<label/>
    <input type='text' id='name' value="Harry"/>

    <label for='email'>email<label/>
    <input type='email' id='email' value="harry@gmail.com"/>

    <label for='age'>age<label/>
    <input type='text' id='age' value="22"/>
<form/>


我试图遍历所有属性,但不确定如何去做
请帮忙

标签: javascript

解决方案


You can loop through all the elements in elements using a for...of loop. You can also create an empty array called form_details, which will hold your resulting object. For each element, you can get its id and value. Then, using an if statement, you can check whether the id and value are defined, and if they are, add them as a key-value pair to your object.

See example below:

function formObj(elems) {
  const form_details = {};
  for(let elem of elems) {
    const key = elem.id;
    const val = elem.value;
    if(key && val)
      form_details[key] = val;
  }
  return form_details;
}

const elements = document.querySelectorAll('form *') //Selects all children of the form element

const details = formObj(elements);
console.log(details);
<form>
    <label for='name'>name</label>
    <input type='text' id='name' value="Harry"/>

    <label for='email'>email</label>
    <input type='email' id='email' value="harry@gmail.com"/>

    <label for='age'>age</label>
    <input type='text' id='age' value="22"/>
<form/>

An easier way would be to change your selector to get the form element, and add the name attribute to each attribute which you want to retrieve. You can then use the FormData Web API to retrieve the entries from your FormData, which you can then turn into an object using Object.fromEntries():

function formObj(elem) {
  const form = new FormData(elem);
  return Object.fromEntries([...form.entries()]);
}

const elements = document.querySelector('form') //Selects all children of the form element

const details = formObj(elements);
console.log(details);
<form>
    <label for='name'>name</label>
    <input type='text' name='name' id='name' value="Harry"/>

    <label for='email'>email</label>
    <input type='email' name='email' id='email' value="harry@gmail.com"/>

    <label for='age'>age</label>
    <input type='text' name='age' id='age' value="22"/>
<form/>


推荐阅读