How to dynamically increment a JSON.stringify

Asked

Viewed 163 times

0

I’m trying to build a dynamic JSON.stringify.

Example:

initial value : var body = JSON.stringify({ "UserName": email });

if(input1Change != 0){
    if(input1 != ""){
        //incrementar o JSON.stringify
    }
}else if(input2Change != 0){
    if(input2 != ""){
        //incrementar o JSON.stringify
    }
}else if(input3Change != 0){
    if(input3 != ""){
        //incrementar o JSON.stringify
    }
}else if(input4Change != 0){
    if(input4 != ""){
        //incrementar o JSON.stringify
    }
}else if(input5Change != 0){
    if(input5 != ""){
        //incrementar o JSON.stringify
    }
}else if(input6Change != 0){
    if(input6 != ""){
        //incrementar o JSON.stringify
    }
}

Goal:

var body = JSON.stringify({ "UserName": email, "Name": input1.value, "Surname": input2.value, "DateBirth": d, "MobilePhone": input4.value });
  • 4

    Why not change the object itself and use the JSON.stringify only at the end?

2 answers

3


Levi, I believe if you change the object obj and only use the method JSON.stringify solve your problem. I think incremetar the JSON.stringify would not be a good idea because the return of it is a string. I suggest doing something similar to the below:

JS:

var obj = {}

obj.Nome = 'Nome'

if(true){
    obj.UserName = 'Nome'
}

if(false){
    obj.Telefone = '(00) 0000-0000'
} else {
    obj.Telefone2 = '(00) 0000-0000'
}

var body = JSON.stringify(obj)

console.log(body)

1

You can do it from n forms, but it all depends on how you wait your exit:

   var ObjUser = {
       UserName:"",
       Name:"",
       Surname:"",
       DateBirth:"",
       MobilePhone:""
    }

    if (input1Change != 0 && input1 != "") {
      ObjUser.UserName = input1;
    }
    if (input2Change != 0 && input2 != "") {
      ObjUser.Name = input2;
    }
    //...etc


    var body = JSON.stringify(ObjUser);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.