Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript append object to existing object

I’m stuck at one point. I have an consolidatedObj object

const consolidatedObj = {
    "flag": "Data Concept",
    "UpdateDC": {
        "id": 732,
        "oId": 695112,
        "cType": "DCON",
        "clientId": 1,
        "aId": 236,
        "fType": "DAT_OWN",
        "details_1": {},
        "details_2": {}
    }
}

and I’ve anotherPayload object which I need to append it to consolidated object

const anotherPayload = {
        flag: 'LOB',
        UpdateLOB: {
          assessmentId: +this.assessmentId,
          lobId: +this.lob['id'],
        }
      };

Below O/P

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const consolidatedObj = {
    "flag": "Data Concept | LOB",
    "UpdateDC": {
        "id": 732,
        "oId": 695112,
        "cType": "DCON",
        "clientId": 1,
        "aId": 236,
        "fType": "DAT_OWN",
        "details_1": {},
        "details_2": {}
    },
    "UpdateLOB": {
          "assessmentId": +this.assessmentId,
          "lobId": +this.lob['id'],
    }
}

How can I add the below object to the existing consolidate object and append the flag value seperated by pipe(|) symbol

>Solution :

const consolidatedObj = {
  "flag": "Data Concept",
  "UpdateDC": {
    "id": 732,
    "oId": 695112,
    "cType": "DCON",
    "clientId": 1,
    "aId": 236,
    "fType": "DAT_OWN",
    "details_1": {},
    "details_2": {}
  }
}

const anotherPayload = {
  flag: 'LOB',
  UpdateLOB: {
    assessmentId: 123,
    lobId: 321,
  }
};

function mergeObjects() {
  let responseObj = {};
  for (let arg = 0; arg < arguments.length; arg++) {
    for (let prop in arguments[arg]) {
      // if property is str and already exist in responseObj = concat with existing
      if (responseObj[prop] && typeof responseObj[prop] === 'string') {
        responseObj[prop] += ' | ' + arguments[arg][prop];
      } else {
        // else just add obj prop to response
        responseObj[prop] = arguments[arg][prop];
      }
    }
  }
  return responseObj;
}

console.log(
  mergeObjects(consolidatedObj, anotherPayload)
);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading