You can use findIndex to find the index in the array of the object and replace it as required:

var item = {...}
var items = [{id:2}, {id:2}, {id:2}];

var foundIndex = items.findIndex(x => x.id == item.id);
items[foundIndex] = item;

This assumes unique IDs. If your IDs are duplicated (as in your example), it's probably better if you use forEach:

items.forEach((element, index) => {
    if(element.id === item.id) {
        items[index] = item;
    }
});
Answer from CodingIntrigue on Stack Overflow
Top answer
1 of 12
475

You can use findIndex to find the index in the array of the object and replace it as required:

var item = {...}
var items = [{id:2}, {id:2}, {id:2}];

var foundIndex = items.findIndex(x => x.id == item.id);
items[foundIndex] = item;

This assumes unique IDs. If your IDs are duplicated (as in your example), it's probably better if you use forEach:

items.forEach((element, index) => {
    if(element.id === item.id) {
        items[index] = item;
    }
});
2 of 12
107

My best approach is:

var item = {...}
var items = [{id:2}, {id:2}, {id:2}];

items[items.findIndex(el => el.id === item.id)] = item;

Reference for findIndex

And in case you don't want to replace with new object, but instead to copy the fields of item, you can use Object.assign:

Object.assign(items[items.findIndex(el => el.id === item.id)], item)

as an alternative with .map():

Object.assign(items, items.map(el => el.id === item.id? item : el))

Functional approach:

Don't modify the array, use a new one, so you don't generate side effects

const updatedItems = items.map(el => el.id === item.id ? item : el)

Note

Properly used, references to objects are not lost, so you could even use the original object reference, instead of creating new ones.

const myArr = [{ id: 1 }, { id: 2 }, { id: 9 }];
const [a, b, c] = myArr;
// modify original reference will change object in the array
a.color = 'green';
console.log(myArr[0].color); // outputs 'green'

This issue usually happens when consuming lists from database and then mapping the list to generate HTML content which will modify the elements of the list, and then we need to update the list and send it back to database as a list.

Good news is, references are kept, so you could organize your code to get advantage of it, and think about a list as an Object with identities for free, which are integers from 0 to length -1. So every time you access any property of your Object, do it as list[i], and you don't lose reference, and original object is changed. Keep in mind that this is useful when your source of truth is only one (the Object created), and your app is always consistently consuming the same Object (not fetching several times from database and assigning it to list along the lifespan of the component).

Bad news is that the architecture is wrong, and you should receive an object by ids (dictionary) if this is what you need, something like

{ 
  1232: { id: 1232, ...},
  asdf234asf: { id: 'asdf234asf', ...},
  ...
}

This way, you don't search in arrays, which is resource consuming. You "just access by key in the object", which is instant and performant.

🌐
JsCraft
js-craft.io › home › javascript – find and replace an object in array
Javascript – find and replace an object in array
November 30, 2023 - For both of these cases, we will use the findIndex() method. If we have a homogeneous object structure of the array we can just compare the elements in the array based on a specific field: const myArray = [ {id: 100, name: "Dan"}, {id: 101, ...
Discussions

javascript - Find and replace object in array (based on id) - Stack Overflow
Got a bit of a puzzle here...I want to loop through allItems and return allItems but replace with any newItems that matches its id. How can I look for a match on id and then replace it with the cor... More on stackoverflow.com
🌐 stackoverflow.com
February 26, 2019
javascript - How to replace item in array? - Stack Overflow
Each item of this array is some number: var items = Array(523,3452,334,31, ...5346); How to replace some item with a new one? For example, we want to replace 3452 with 1010, how would we do this? More on stackoverflow.com
🌐 stackoverflow.com
javascript - How to find and replace an object with in array of objects - Stack Overflow
Find object by id in an array of JavaScript objects · EDIT: Forgot about the replacement piece. More on stackoverflow.com
🌐 stackoverflow.com
Find and replace value inside an array of objects javascript - Stack Overflow
A POST request is coming in with the deviceID of eI2K-6iUvVw:APA, all i want to do is to iterate the array, find the deviceID and change the enabled value to false. More on stackoverflow.com
🌐 stackoverflow.com
February 25, 2019
🌐
DEV Community
dev.to › albertomontalesi › find-and-replace-elements-in-array-with-javascript-2e4n
Find and Replace elements in Array with JavaScript - DEV Community
May 10, 2021 - As you can see, using findIndex we can easily find and then replace Objects in an Array of Objects.
🌐
Itsourcecode
itsourcecode.com › home › how to find and replace object in an array javascript?
How to Find and Replace Object in an Array JavaScript?
September 6, 2023 - As you can see in our given example: we use the findIndex method to find the index of the object with the name property equal to ‘Andrea.’ · If the object is found (i.e., index is not -1), the splice method is used to remove one element at the specified index and replace it with a new object { name: ‘Itsourcecode’, age: 21 }. ... This method allows you to iterate over each element in the array and check if it satisfies a certain condition.
🌐
Delft Stack
delftstack.com › home › howto › javascript › replace object in array javascript
How to Replace Object in an Array in JavaScript | Delft Stack
February 2, 2024 - Suppose we want to replace the first two objects with different colors names in the array. We can do that using the index of these objects. At index 0, we have Red, and at index 1, we have Blue. We can replace these two colors using selectedColors[], give the index number of the object we want to replace, and assign a new color.
🌐
IQCode
iqcode.com › code › javascript › find-and-replace-value-in-array-of-objects-javascript
find and replace value in array of objects javascript Code Example
September 27, 2021 - let arr = [ { "enabled": true, "deviceID": "eI2K-6iUvVw:APA", }, { "enabled": true, "deviceID": "e_Fhn7sWzXE:APA", }, { "enabled": true, "deviceID": "e65K-6RRvVw:APA", }, ]; const id = 'eI2K-6iUvVw:APA'; arr.find(v => v.deviceID === id).enabled = false; console.log(arr); ... Unlock the power of data and AI by diving into Python, ChatGPT, SQL, Power BI, and beyond.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-replace-an-object-in-an-array-with-another-object-based-on-property
How to Replace an Object in an Array with Another Object Based on Property ? - GeeksforGeeks
July 23, 2025 - If the index is found, the splice function is used to replace the existing object with a new one. This approach directly modifies the original array. Example: Demonstration to find the index of the element based on the property using findIndex and then replace concatenate using splice.
Find elsewhere
🌐
30 Seconds of Code
30secondsofcode.org › home › javascript › array › replace or append array value
Replace or append a value in a JavaScript array - 30 seconds of code
March 23, 2024 - const replaceOrAppend = (arr, val, compFn) => { const res = [...arr]; const i = arr.findIndex(v => compFn(v, val)); if (i === -1) res.push(val); else res.splice(i, 1, val); return res; }; const people = [ { name: 'John', age: 30 }, { name: 'Jane', age: 28 }, ]; const jane = { name: 'Jane', age: 29 }; const jack = { name: 'Jack', age: 28 }; replaceOrAppend(people, jane, (a, b) => a.name === b.name); // [ { name: 'John', age: 30 }, { name: 'Jane', age: 29 } ] replaceOrAppend(people, jack, (a, b) => a.name === b.name); // [ // { name: 'John', age: 30 }, // { name: 'Jane', age: 28 }, // { name: 'J
Top answer
1 of 16
295

You can use Array#map with Array#find.

arr1.map(obj => arr2.find(o => o.id === obj.id) || obj);

Show code snippet

var arr1 = [{
    id: '124',
    name: 'qqq'
}, {
    id: '589',
    name: 'www'
}, {
    id: '45',
    name: 'eee'
}, {
    id: '567',
    name: 'rrr'
}];

var arr2 = [{
    id: '124',
    name: 'ttt'
}, {
    id: '45',
    name: 'yyy'
}];

var res = arr1.map(obj => arr2.find(o => o.id === obj.id) || obj);

console.log(res);
Run code snippetEdit code snippet Hide Results Copy to answer Expand

Here, arr2.find(o => o.id === obj.id) will return the element i.e. object from arr2 if the id is found in the arr2. If not, then the same element in arr1 i.e. obj is returned.

2 of 16
14

There is always going to be a good debate on time vs space, however these days I've found using space is better for the long run.. Mathematics aside let look at a one practical approach to the problem using hashmaps, dictionaries, or associative array's whatever you feel like labeling the simple data structure..

    var marr2 = new Map(arr2.map(e => [e.id, e]));
    arr1.map(obj => marr2.has(obj.id) ? marr2.get(obj.id) : obj);

I like this approach because though you could argue with an array with low numbers you are wasting space because an inline approach like @Tushar approach performs indistinguishably close to this method. However I ran some tests and the graph shows how performant in ms both methods perform from n 0 - 1000. You can decide which method works best for you, for your situation but in my experience users don't care to much about small space but they do care about small speed.



Here is my performance test I ran for source of data

var n = 1000;
var graph = new Array();
for( var x = 0; x < n; x++){
  var arr1s = [...Array(x).keys()];
  var arr2s = arr1s.filter( e => Math.random() > .5);
  var arr1 = arr1s.map(e => {return {id: e, name: 'bill'}});
  var arr2 = arr2s.map(e => {return {id: e, name: 'larry'}});
  // Map 1
  performance.mark('p1s');
  var marr2 = new Map(arr2.map(e => [e.id, e]));
  arr1.map(obj => marr2.has(obj.id) ? marr2.get(obj.id) : obj);
  performance.mark('p1e');
  // Map 2
  performance.mark('p2s');
  arr1.map(obj => arr2.find(o => o.id === obj.id) || obj);
  performance.mark('p2e');
  graph.push({ x: x, r1: performance.measure('HashMap Method', 'p1s', 'p1e').duration, r2: performance.measure('Inner Find', 'p2s','p2e').duration});
}
🌐
CodeSpeedy
codespeedy.com › home › replace an object in an array with another object in javascript
Replace an object in an array with another object in JavaScript
February 16, 2024 - JavaScript program to replace an ... 'David', age: 28}; //To find the index of the object that we want to replace const index = myArray.findIndex(item => item.name === 'Rayan'); //To replace the object with the new object ...
🌐
Reddit
reddit.com › r/learnjavascript › best way to find and replace all instances if a string in an array of strings?
r/learnjavascript on Reddit: Best way to find and replace all instances if a string in an array of strings?
January 6, 2023 -

Hi,

I have some code Im doing in google apps-scripts that involves a lot of array manipulation. Currently I have a bunch of arrays a strings and they are full of data and some of the strings are either empty strings or "x" and I need to make the empty strings and the x’s be replaced with a new string “Closed”. The length of the arrays are different every time I run the code, and the number of emptys and xs are too.

Currently I am doing this by iterating through each of the arrays and checking each value for the replaceable values and replacing the matches. This is rather slow and feels like there is probably a better solution to this. So i went looking and there are methods like find() and include() and map() that all might be of use here but I wanted to ask what the optimal way to do it would be.

Code snip:

var arr={"826", "7161", "", "", "x", "927", "hah", "hg7)", "x"}
Code here
Logger.log(arr.join(", ")

Expected output:

826, 7161, Closed, Closed, Closed, 927, hah, hg7), Closed

🌐
CodersTechZone
coderstechzone.com › home › find and replace object in array javascript: 4 key techniques
Find And Replace Object In Array JavaScript: 4 Key Techniques
June 17, 2024 - The two basic use cases for finding ... is to search through an array for a single item, then change a few of its properties. One more is to update every object in an array that meets a particular set of search parameters. Keep in mind that if you need to find and replace only a single object within an array, then it’s best to use the Array.findIndex() method...
🌐
Reddit
reddit.com › r/learnjavascript › how do i replace all object values in an array with values from another array?
r/learnjavascript on Reddit: How do I replace all object values in an array with values from another array?
December 27, 2022 -

Let's say I have an array called data and it contains the following:

data: [
    {
        id: 100,
        name: "something",
        code_block: "x\ny\nz\na\nresult:touchdown\nasd\n"
    },
    {
        id: 200,
        name: "somethingElse",
        code_block: "a\nb\nc\nd\nresult:touchdown\nasd\n"
    }
]

What I'm trying to do is iterate through the code_block property to extract out a string (result:touchdown) and replace the original value of code_block with that string. The problem is I'm not sure how I can perform the array methods like .map and such and still carry over the id and name properties.

Would you guys recommend that I make a shallow copy of the data object, iterate through code_block, and then replace that property on the original data object with the new array? Is there even a way to do this, or is there a better approach to what I'm doing here?

Thanks in advance for all your help!