Search code examples
javascriptservicenow

Create two identical object with different value javascript


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);

Solution

  • 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
      )
    }