如何通过JavaScript将注册表单数据存入以firstname为键的父对象
实现注册表单数据存储为指定格式的对象
核心思路
- 读取表单中
firstname、lastname、email、password的输入值 - 以
firstname的内容作为父对象的键,将所有字段信息封装为对应的子对象 - 可选择将对象存储到本地存储或作为变量使用
HTML 表单示例
<form id="registrationForm"> <input type="text" id="firstname" placeholder="First Name" required> <input type="text" id="lastname" placeholder="Last Name" required> <input type="email" id="email" placeholder="Email" required> <input type="password" id="password" placeholder="Password" required> <button type="submit">Register</button> </form>
JavaScript 实现代码
// 获取表单元素 const form = document.getElementById('registrationForm'); // 监听表单提交事件 form.addEventListener('submit', function(e) { e.preventDefault(); // 阻止默认提交行为 // 读取输入字段值 const firstname = document.getElementById('firstname').value.trim(); const lastname = document.getElementById('lastname').value.trim(); const email = document.getElementById('email').value.trim(); const password = document.getElementById('password').value; // 构造目标格式的对象 const userData = { [firstname]: { firstname: firstname, lastname: lastname, email: email, password: password } }; // 示例:存储到localStorage localStorage.setItem('registeredUsers', JSON.stringify(userData)); // 若需累积多个用户,可合并现有数据 // let existingUsers = JSON.parse(localStorage.getItem('registeredUsers')) || {}; // existingUsers = {...existingUsers, ...userData}; // localStorage.setItem('registeredUsers', JSON.stringify(existingUsers)); console.log('存储的数据:', userData); alert('注册完成'); form.reset(); // 重置表单 });
重要提示
- 密码安全:实际项目中禁止明文存储密码,必须使用哈希算法(如bcrypt)加密后再保存
- 输入验证:建议添加邮箱格式检查、密码强度校验等逻辑,提升数据有效性
内容的提问来源于stack exchange,提问作者Kondaveti Charan
相关产品推荐
相关产品推荐

