javascript - 如何遍历所有属性并将值作为对象返回
问题描述
我需要编写一个函数,该函数接受一个参数列表,该参数是一个元素列表。元素都是labels
和inputs
。函数应该创建一个对象,其中的文本是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/>
我试图遍历所有属性,但不确定如何去做
请帮忙
解决方案
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/>
推荐阅读
- javascript - 在反应应用程序的函数调用中使用时,Axios post 不返回数据
- javascript - JavaScript 函数不适用于第二个 HTML 文件,因为它是由第一个 HTML 文件中的按钮触发的
- c - 处理 sbrk() 失败的合规方法是什么?
- java - 如何获取任何编码 Java 字符串的 5 个字符?
- visual-studio - 硒:没有可用的测试。确保测试发现者和执行者已注册并且平台和框架版本设置是适当的
- android - Android Support plugin for IntelliJ IDEA (or Android Studio) cannot open this project
- php - Laravel 5.8 - 路由参数的指定类型模型
- python - 在转换为 Pandas 中的日期时间列之前删除对象中的某些字符
- azure-devops - Azure DevOps TFS Repos:链接到标记内的内部文件
- sql - Oracle 将查询结果与多个连接与一个表进行比较