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

How to add new data items to an existing JavaScript object

I am trying to add new items to an existing JavaScript object as shown below. But both methods throw errors. I could create two separate objects by hard-coding with these values, but want to avoid it.

var defaultAmountTypeData = [
  { text: "Dollar", value: "D" },
  { text: "Percent", value: "P" },
  { text: "Sale", value: "S" },
];
var updatedAmountTypeData = [
  { text: "Dollar", value: "D" },
  { text: "Percent", value: "P" },
  { text: "Sale", value: "S" },
  { text: "New Amount", value: "NA" },
  { text: "New Percent", value: "NP" },
];

Tried the following:

Solution 1:

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

var updatedAmountTypeData = [
  defaultAmountTypeData,
  { text: "New Amount", value: "NA" },
  { text: "New Percent", value: "NP" },
];

Solution 2:

var updatedAmountTypeData = getUpdatedAmountTypeData(){
  var newobj = Object.assign(defaultAmountTypeData, {
    text: "New Amount",
    value: "NA",
  });
  newobj = Object.assign(newobj, { text: "New Percent", value: "NP" });
  return newobj;
}

>Solution :

Use ellipsis to combine arrays.

var updatedAmountTypeData =
    [
        ...defaultAmountTypeData,
        { text: "New Amount", value: "NA" },
        { text: "New Percent", value: "NP" }
    ];
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