I am fairly new to JavaScript and I am wondering how I can take the value of a variable and set it as the key name to the corresponding field. I came across this when I was making a webapp, and what it does is take in signup data and puts it into a JS object to be sent to my API.
signup.html:
<form id="signup-form" name ="signup-form">
<input class="login-form-field" type="text" name="user" placeholder="username">
<input class="login-form-field" type="text" name="email" placeholder="email">
<input class="login-form-field" type="password" name="dob" placeholder="date of birth">
<br>
<!--<button class="actionButton"></button>-->
<INPUT TYPE="button" NAME="button" Value="Click" onClick="signupData(this.form)">
</form>
Below you will see that when I use dob, it names the key dob and sets the field to the value of it. When I set the key to variable user it does not set the key to the value of variable user as I initially thought it would. How can I set the key to the value of variable user?
function signupData(form) //add to this script
{
console.log("signup data is starting");
var user = form.user.value;
var email = form.email.value;
var dob = form.dob.value;
//genSKey();
// genPKey();
//var skey = getSKey();
//var enUser = encryptMes(user);
//var enEmail = encryptMes(email);
//var endob = encryptMes(dob);
var data = {name : "LifeNet", members : {user : {profilePic : {}, dob, listeners : {}, listening : {}, friends : {}, requested : {}, blocked : {}, channel: false}}}
apiPost({data});
//pass the signup function in here
//hash the variables and send to celox network
console.log(JSON.stringify({data}));
//alert (`copy and save your Private Key to somewhere safe: ${skey}`);
}
</script>
Below you will see that it does not set the name to what I input in the signup form. Browser:
{"data":{"name":"LifeNet","members":{"user":{"profilePic":{},"dob":"01/25/2000","listeners":{},"listening":{},"friends":{},"requested":{},"blocked":{},"channel":false}}}}
help is much appreciated, thank you.
Answer as mentioned by Terry:
append to the existing object with bracket notation.
var user = form.user.value;
var email = form.email.value;
var dob = form.dob.value;
var data = {name:"LifeNet", members:{}};
data.members[user] = {profilePic:{},dob, listeners:{}, listening:{}, friends:
{}, requested:{}, blocked:{}, channel:false}