Bacancy Technology
Bacancy Technology represents the connected world, offering innovative and customer-centric information technology experiences, enabling Enterprises, Associates and the Society to Rise™.
12+
Countries where we have happy customers
1050+
Agile enabled employees
06
World wide offices
12+
Years of Experience
05
Agile Coaches
14
Certified Scrum Masters
1000+
Clients projects
1458
Happy customers
Artificial Intelligence
Machine Learning
Salesforce
Microsoft
SAP
October 17, 2023
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);