Yeah, it's pretty simple: const result = data.map(obj => ({ ...obj, code_block: obj.code_block.match(/result:.+/)[0] })) Answer from albedoa on reddit.com
๐ŸŒ
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!

๐ŸŒ
JsCraft
js-craft.io โ€บ home โ€บ javascript โ€“ find and replace an object in array
Javascript โ€“ find and replace an object in array
November 30, 2023 - 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, name: "Bob"}, {id: 102, name: "Joe"}, ] const searchedObj = {id: 101, name: "Bob"} const replacingObj = {id: 105, name: "Todd"} const i = myArray.findIndex(x => x.id === searchedObj.id) myArray[i] = replacingObj console.log(myArray)
Discussions

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
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
javascript - Replacing objects in array - Stack Overflow
Doesn't work in Internet Explorer 11. There's a polyfill though: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/โ€ฆ 2020-01-31T08:58:57.26Z+00:00 ... I needed something were I have an array and I want to push another object onto that array if the object is not present in the array. More on stackoverflow.com
๐ŸŒ stackoverflow.com
Replace values in array of object with values from another array in JavaScript - Stack Overflow
This should be a small task, but could not figure it out. I've an array of objects named 'A' More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
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...
๐ŸŒ
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. Let's say we are not interested in replacing a value but we just want to remove it, we will now look at different ways of doing so.
๐ŸŒ
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 - 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.
Find elsewhere
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});
}
๐ŸŒ
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: 'Jack', age: 28 } // ] ... Easily remove duplicates from a JavaScript array using the built-in Set object, and learn a few other tricks along the way. ... When working with JavaScript arrays, you might need the minimum or maximum value.
๐ŸŒ
Bobby Hadz
bobbyhadz.com โ€บ blog โ€บ javascript-replace-element-in-array
How to Replace an Element in an Array in JavaScript | bobbyhadz
The forEach() method is useful if you need to replace all occurrences of the value in the array. You can learn more about the related topics by checking out the following tutorials: Filter an Array with Multiple Conditions in JavaScript ยท Filter ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ javascript โ€บ how-to-replace-an-item-from-an-array-in-javascript
JavaScript - Replace an Item from JS Array - GeeksforGeeks
July 12, 2025 - ... The splice() method in JavaScript is another way to replace items in an array. This method allows you to remove items and insert new ones at the specified position in the array.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ 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
February 2, 2024 - This method used the map function to create a new array by iterating over the original array. It checks a specific property to identify the target object for replacement. If the condition is met, a new object with updated values is returned; otherwise, the original object is retained. Example: Demonstrate the creation of a new array by applying a function to each element in the existing array using a map().
๐ŸŒ
The Web Dev
thewebdev.info โ€บ home โ€บ how to replace objects in array with javascript?
How to replace objects in array with JavaScript? - The Web Dev
June 5, 2022 - Otherwise, it returns the obj object in arr1. To replace objects in array with JavaScript, we can use the array map method. How to merge duplicate objects in array of objects with JavaScript?
๐ŸŒ
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 - Replacing an object in an array in JavaScript can be achieved through various methods, such as using the map() method, the splice() method, or a for loop with the splice method. These methods allow you to locate the object you want to replace, ...
๐ŸŒ
Better Programming
betterprogramming.pub โ€บ more-javascript-array-tips-replacing-and-mapping-entries-2fb4c0b139d8
More JavaScript Array Tips. Replacing and mapping entries | by John Au-Yeung | Better Programming
December 17, 2019 - There are a few ways to replace specific values from an array. We can use the indexOf method to get the first occurrence of an array and then use the index to assign a new value to the entry in that array index.
๐ŸŒ
Peterbe.com
peterbe.com โ€บ plog โ€บ replace-an-item-in-an-array-without-mutation-in-javascript
Replace an item in an array, by number, without mutation in JavaScript (ES6) - Peterbe.com
... const index = 1; const ... immediately obvious to me but writing it down will help me remember. ... function replaceAt(array, index, value) { const ret = array.slice(0); ret[index] = value; return ret; } const newArray ...