2

I am using typescript, I have an existing JSON response below coming through an API,

{
    "product":{
    "prodId": "PROD100"
    },
    "packages":{
    "pkgId": "PKG137"
    },
    "discount":"50",
    "periodFrom":null,
    "periodTo":null,
    "totalAmount": "599",
    "isActive": "false"
}

I have another small JSON, which I want to append at the top of it

"customer":{
    "custId":"CUST1002"
    },

Final Structure:

{
    "customer":{
    "custId":"1002"
    },
    "product":{
    "prodId": "PROD100"
    },
    "packages":{
    "pkgId": "PKG137"
    },
    "discount":"50",
    "periodFrom":null,
    "periodTo":null,
    "totalAmount": "599",
    "isActive": "false"
}

How do I achieve the same using push or unshift, or is there any best practice for the same in JavaScript or in typescript. Kindly suggest me

user9634982
  • 565
  • 5
  • 24

2 Answers2

3

You can use the object spread syntax:

const newJSON = { ...toAppend, ...original };

const original = {
  "product": {
    "prodId": "PROD100"
  },
  "packages": {
    "pkgId": "PKG137"
  },
  "discount": "50",
  "periodFrom": null,
  "periodTo": null,
  "totalAmount": "599",
  "isActive": "false"
}


const toAppend = {
  "customer": {
    "custId": "CUST1002"
  },
}
const newJSON = { ...toAppend, ...original };
console.log(newJSON);
DecPK
  • 24,537
  • 6
  • 26
  • 42
blaumeise20
  • 2,148
  • 8
  • 26
1

Using the spread-operator:

const obj = {
  "product": { "prodId": "PROD100" },
  "packages": { "pkgId": "PKG137" },
  "discount": "50",
  "periodFrom": null,
  "periodTo": null,
  "totalAmount": "599",
  "isActive": "false"
};
const toAdd = {
  "customer": { "custId":"CUST1002" }
};

const res = { ...toAdd, ...obj };

console.log(res);
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48