Skip to content

Update array using spread operator | Example code

  • by

Use a mix of the map and the spread operator to update the array using the spread operator. You can set the value after you’ve created your new array.

Update the array using the spread operator

Simple example code.

<!DOCTYPE html>
<html>
<body>

  <script>
    let array = [{id:1,name:'One'}, 
              {id:2, name:'Two'}, 
              {id:3, name: 'Three'}];

    let array2 = array.map(a => {return {...a}})

    array2.find(a => a.id == 2).name = "Not Two";

    console.log(array);
    console.log(array2);
  </script>

</body>
</html> 

Output:

Update array using spread operator

Or you can do it in the .map

let array = [{id:1,name:'One'}, {id:2, name:'Two'}, {id:3, name: 'Three'}];

let array2 = array.map(a => {
  var returnValue = {...a};

  if (a.id == 2) {
    returnValue.name = "Not Two";
  }

  return returnValue
})

console.log(array2);

Output:

[
  {
    "id": 1,
    "name": "One"
  },
  {
    "id": 2,
    "name": "Not Two"
  },
  {
    "id": 3,
    "name": "Three"
  }
]

Or you can use the spread operator to update an array by creating a new array that contains the elements of the original array, along with any additional elements you want to add.

// Original array
const numbers = [1, 2, 3, 4, 5];

// Add a new element to the end of the array using spread operator
const newNumbers = [...numbers, 6];

console.log(newNumbers); // [1, 2, 3, 4, 5, 6]

You can also use the spread operator to update specific elements of an array by using array index notation.

// Original array
const fruits = ['apple', 'banana', 'orange'];

// Update the second element using spread operator
const newFruits = [
  ...fruits.slice(0, 1),
  'pear',
  ...fruits.slice(2)
];

console.log(newFruits); // ['apple', 'pear', 'orange']

Do comment if you have any doubts or suggestions on this JS operator topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *