Here’s an example how you can append new key value in Array, without replacing old value in javascript:

Code:

let arrayOfObjects = [
  { key1: "value1", key2: "value2" },
  { key1: "value3", key2: "value4" }
];

let newKeyValue = [{ key1: "value5", key2: "value6" }];

arrayOfObjects = newKeyValue;

console.log(arrayOfObjects);

As shown in the above example, if we try to re-assign an array with a new value then the old value will be replaced by the new value. To solve this problem, consider below example:

let arrayOfObjects = [
  { key1: "value1", key2: "value2" },
  { key1: "value3", key2: "value4" }
];

let newKeyValue = [{ key1: "value5", key2: "value6" }];

arrayOfObjects = [...arrayOfObjects, ...newKeyValue];

console.log(arrayOfObjects);

Explanation:

As shown in the above example, using the spread operator we can append new values in the array without removing old values. Here we can also use the concat method to concat both arrays.

let arrayOfObjects = [
  { key1: "value1", key2: "value2" },
  { key1: "value3", key2: "value4" }
];

let newKeyValue = [{ key1: "value5", key2: "value6" }];

arrayOfObjects = arrayOfObjects.concat(newKeyValue);

console.log(arrayOfObjects);

 

Support On Demand!

                                         
JavaScript