You can use a mix of .map and the ... spread operator

You can set the value after you've created your new array

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);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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(array);
console.log(array2);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer from George on Stack Overflow
🌐
Medium
medium.com › @deluxan.m › update-javascript-array-using-spread-operator-c5df3c67db97
Update javascript array using spread operator | by Deluxan Mariathasan | Medium
February 15, 2025 - If you need to update specific properties within some of these objects before adding them to the new array (while still keeping others unchanged), you could use methods like `.map()` or object destructuring with updates before spreading them into your final array.
🌐
JavaScript in Plain English
javascript.plainenglish.io › how-to-easily-update-your-objects-with-the-spread-operator-8f3dfdbcf956
How to Easily Update Your Objects with the Spread Operator | by Piero Borrelli | JavaScript in Plain English
July 30, 2024 - ‘Spreading’ your objects is an easy operation. It works in a similar fashion to common arrays. In this case, instead of ‘spreading’ array items, you will spread key-value pairs.
🌐
EyeHunts
tutorial.eyehunts.com › home › update object in array javascript using the spread operator | example
Update object in array JavaScript using the spread operator | Code
February 23, 2023 - Use both method map and the spread operator to update objects in array JavaScript. set the value after you’ve created your new array. Simple example code updates the name of the second element (with id 2) and copies the array to a new array ...
🌐
Brian Childress
brianchildress.co › update-object-using-the-spread-operator-javascript
Update an Object Using the Spread Operator - Brian Childress
April 13, 2021 - The Spread Operator introduced into the JavaScript language as part of the ECMAScript 6 (ES6) specification in 2015 is a powerful syntax. The spread operator allows us to operator on any iterable element including objects and arrays...
🌐
EyeHunts
tutorial.eyehunts.com › home › update array using spread operator | example code
Update array using spread operator | Example code
March 22, 2023 - // Original array const numbers ...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....
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Operators › Spread_syntax
Spread syntax (...) - JavaScript - MDN Web Docs - Mozilla
May 22, 2026 - The spread (...) syntax allows an iterable, such as an array or string, to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected. In an object literal, the spread syntax enumerates the properties of an object and adds the key-value ...
🌐
GitHub
gist.github.com › gorangajic › e902c2ee994260b3348d
es6 spread immutable cheatsheet · GitHub
That is the reason why in the above example he needs to do this: ... You can see the spread operator in state[index] in order to get a shallow copy of the current object in the state array giving with that a new reference in the newState array.
Find elsewhere
🌐
Educative
educative.io › home › courses › simplifying javascript: a handy guide for software engineers › tip 12: update information with object spread
Update JavaScript Objects Efficiently with Object Spread Operator
Explore how to use the object spread operator to update and merge JavaScript objects more cleanly than Object.assign(). Understand its behavior in overwriting keys and avoiding mutations. This lesson helps you write modern, maintainable code by adopting a widely embraced syntax. We'll cover the following... ... You saw in the previous tip how you can use Object.assign() to make copies of objects and how you can overwrite object values with new values from another object.
🌐
DEV Community
dev.to › abhay_yt_52a8e72b213be229 › mastering-the-spread-operator-for-objects-and-arrays-in-javascript-4efp
Mastering the Spread Operator for Objects and Arrays in JavaScript - DEV Community
December 17, 2024 - In cases where you want to modify an individual object in an array of objects, you can use the spread operator to copy the objects and update specific properties.
Top answer
1 of 3
4

The main reason I can see for this is to create a shallow copy of the object, so that if you perform any operations on the copy, it won't mutate the original. This would be especially useful in a functional programming paradigm where you don't want to mutate any shared objects/maintain a shared state.

However, as I mentioned, this only creates a shallow copy (as opposed to a deep copy), so that if any of the properties of the object are themselves mutable (such as an array property), then those properties would still be able to be mutated.

Edit: From the question in the comments, and building off of what @AdiH mentioned in their answer, it doesn't seem to make any sense to update post.title before creating the shallow copy as this would mutate the original object. It's possible that the author intended for this change to be reflected in both the original and the copy, but for any further changes to be reflected only in the copy

const x = { a: 'b', c: 'd', d: [] };

const copy = { ...x };
copy.a = 'c';
console.log(x); // unchanged

const same = x;
same.a = 'c';
console.log(x); // changed

copy.d.push('e');
console.log(x); // x.d has been changed

2 of 3
2

I can see your confusion. I think the example is not great. One can only guess what the author had in mind but if he or she intended to enforce immutability I would not have done post.title = "Updated" since it obviously mutates post.

Instead I would have done post[index] = { ...post, title: "Updated"} see examples of JS Spread syntax.

So yes, I'm also unable to guess the motivation behind that example.

🌐
SamanthaMing
samanthaming.com › tidbits › 92-6-use-cases-of-spread-with-array
6 Use Case of Spread with Array in JavaScript | SamanthaMing.com
6 ways to use the Spread operator with Array in JavaScript. Use it to merge or clone an array. Or use it to convert iterables to an array.
🌐
SitePoint
sitepoint.com › blog › javascript › quick tip: how to use the spread operator in javascript
Quick Tip: How to Use the Spread Operator in JavaScript — SitePoint
November 7, 2024 - The spread operator can be used to create new arrays from existing arrays or other iterable objects that include the Symbol.iterator() method. These are objects that can be iterated using the for...of loop. For example, it can be used to clone arrays. If you simply assign a new array the value of an existing array, making changes to the new one will update the existing one...
🌐
DEV Community
dev.to › andyrewlee › cheat-sheet-for-updating-objects-and-arrays-in-react-state-48np
Cheat Sheet for Updating Objects and Arrays in React State - DEV Community
May 4, 2020 - const handleAdd = (todo) => { const newTodos = Object.assign({}, todos); newTodos[todo.id] = todo; setTodos(newTodos); } We can use spread operator to create shallow copy as well. const handleAdd = (todo) => { const newTodos = {...todos}; newTodos[todo.id] = todo; setTodos(newTodos); } Similar to arrays, there's a shortcut for doing this in one line:
Top answer
1 of 8
58

use Array.slice

this.setState({
  images: [
    ...this.state.images.slice(0, 4),
    updatedImage,
    ...this.state.images.slice(5),
  ],
});

Edit from original post: changed the 3 o a 4 in the second parameter of the slice method since the second parameter points to the member of the array that is beyond the last one kept, it now correctly answers the original question.

2 of 8
32

Once the change array by copy proposal is widely supported (it's at Stage 3, so should be finding its way into JavaScript engines), you'll be able to do this with the new with method:

// Using a Stage 3 proposal, not widely supported yet as of Nov 17 2022
this.setState({images: this.state.images.with(4, updatedImage)});

Until then, Object.assign does the job:

this.setState({images: Object.assign([], this.state.images, {4: updatedImage}));

...but involves a temporary object (the one at the end). Still, just the one temp object... If you do this with slice and spreading out arrays, it involve several more temporary objects (the two arrays from slice, the iterators for them, the result objects created by calling the iterator's next function [inside the ... handle], etc.).

It works because normal JS arrays aren't really arrays1 (this is subject to optimization, of course), they're objects with some special features. Their "indexes" are actually property names meeting certain criteria2. So there, we're spreading out this.state.images into a new array, passing that into Object.assign as the target, and giving Object.assign an object with a property named "4" (yes, it ends up being a string but we're allowed to write it as a number) with the value we want to update.

Live Example:

const a = [0, 1, 2, 3, 4, 5, 6, 7];
const b = Object.assign([], a, {4: "four"});
console.log(b);

If the 4 can be variable, that's fine, you can use a computed property name (new in ES2015):

let n = 4;
this.setState({images: Object.assign([], this.state.images, {[n]: updatedImage}));

Note the [] around n.

Live Example:

const a = [0, 1, 2, 3, 4, 5, 6, 7];
const index = 4;
const b = Object.assign([], a, {[index]: "four"});
console.log(b);


1 Disclosure: That's a post on my anemic little blog.

2 It's the second paragraph after the bullet list:

An integer index is a String-valued property key that is a canonical numeric String (see 7.1.16) and whose numeric value is either +0 or a positive integer ≤ 253-1. An array index is an integer index whose numeric value i is in the range +0 ≤ i < 232-1.

So that Object.assign does the same thing as your create-the-array-then-update-index-4.