Home > front end >  How to add new data items to an existing JavaScript object
How to add new data items to an existing JavaScript object

Time:11-16

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:

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

CodePudding user response:

Use ellipsis to combine arrays.

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