typescript 将对象追加到现有对象

yacmzcpb  于 2023-04-07  发布在  TypeScript
关注(0)|答案(1)|浏览(129)

我在一个点卡住了。我有一个consolidatedObj对象

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

我有一个anotherPayload对象,我需要将它附加到统一对象

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

低于O/P

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'],
    }
}

如何将下面的对象添加到现有的合并对象中,并附加由pipe(|)符号分隔的标志值

biswetbf

biswetbf1#

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

相关问题