Home > Back-end >  Create two identical object with different value javascript
Create two identical object with different value javascript

Time:07-07

i have to create 2 identical object, one with value 'home' and other with value 'mailing' if the condition is true I send them both otherwise I send only 'home', what can I do?

it's correct to do that?

var arrayObj = []
var reqBodyAddress = {};
    
    reqBodyAddress.startDate = new GlideDateTime(current.u_data_inizio_contratto).getNumericValue();
    reqBodyAddress.addressType = function(){
    var objAddressType1 = {
            home:'home'
        }
    var objAddressType2 = {
            mailing:'mailing'
        }
        if(current.u_domicilio == true){
            reqBodyAddress.addressType = objAddressType1   objAddressType2;
            }else{
            reqBodyAddress.addressType = objAddressType1;
        }
    };

arrayObj.push(reqBodyAddress);

var sReqBodyData = JSON.stringify(arrayObj);

CodePudding user response:

use this

reqBodyAddress.addressType = {
                home:'home'
            ...(current.u_domicilio && {mailing:'mailing'})

}

it's more readable first, and work correct. try to use const and let and avoid to use var for declaring variable in your js code.

your addressType property must get an object for value, right? so why do you use function for its value? also you can't merge two object with operator. i hope this code solve your problem.

CodePudding user response:

Use Object.assign(target, ...sources) [read more] which copies multiple source objects into a target object, and then use a condition on the second object. similar to this:

let a = {foo:'foo'}
let b = {bar:'bar'}

let c = Object.assign(a, (false? b : null));
console.log(c) // {foo:"foo"}

let d = Object.assign(a, (true? b : null));
console.log(d) // {foo:"foo", bar:"bar"}

Test it here

For your case, it would look like this:

reqBodyAddress.addressType = function(){
  var objAddressType1 = {
    home:'home'
  }
  
  var objAddressType2 = {
    mailing:'mailing'
  }
  
  reqBodyAddress.addressType = Object.assign(
    objAddressType1, // target
    (current.u_domicilio?  objAddressType2 : null) // source
  )
}

Note that this doesn't return a copy and will edit the target object. If you don't want to edit any objects when using this function, you can make your target an empty object {} and put all your objects as sources like this:

reqBodyAddress.addressType = function(){
  var objAddressType1 = {
    home:'home'
  }
  
  var objAddressType2 = {
    mailing:'mailing'
  }
  
  reqBodyAddress.addressType = Object.assign(
    {}, // empty target
    objAddressType1, // source 1
    (current.u_domicilio?  objAddressType2 : null) // source 2
  )
}
  • Related