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.
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.
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});
}
javascript - How to find and replace an object with in array of objects - Stack Overflow
Add/Replace object from array of objects JavaScript - Stack Overflow
javascript - How to replace item in array? - Stack Overflow
Replace item in array of objects with Javascript - Stack Overflow
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!
Different ways to achieve this.
- By using Object.assign() method. It returns the modified target object.
const data = [{
"id": 1,
"name": "January",
"abc": "abc",
"xyz": "xyz"
}, {
"id": 2,
"name": "February",
"abc": "abc",
"xyz": "xyz"
}];
const target = data.find((obj) => obj.id === 2);
const source = {
id: 2,
name: 'New Month',
abc: 'abc123',
xyz: 'someValue'
};
Object.assign(target, source);
console.log( data );
- By using array.map() method which creates a new array populated with the results of calling a provided function on every element in the calling array.
const data = [{"id": 1,"name": "January","abc": "abc","xyz": "xyz"}, {"id": 2,"name": "February","abc": "abc","xyz": "xyz"}];
const modifiedObj = {"id": 2,"name": "New month","abc": "1234abc","xyz": "someVlaue"};
const result = data.map((item) => item.id === modifiedObj.id ? modifiedObj : item);
console.log(result);
You can use Object.assign() with find() as follows:
const data = [{
"id": 1,
"name": "January",
"abc": "abc",
"xyz": "xyz"
}, {
"id": 2,
"name": "February",
"abc": "abc",
"xyz": "xyz"
}];
Object.assign(
//find the desired object
data.find(({id,name,abc,xyz}) => id === 2),
//pass these new values
{name:"New Month",abc:"abc123",xyz:"someValue"}
);
console.log( data );
You could look for the index and update the array, if found or push the object.
var array = [{ name: 'test1', id: 1, data: { a: 1 } }, { name: 'test2', id: 2, data: { a: 2 } }],
object = { name: 'test3', id: 3, data: { a: 3 } },
index = array.findIndex(({ name, id }) => name === object.name && id === object.id);
if (index === -1) {
array.push(object);
} else {
array[index] = object;
}
console.log(array);
Wraping @Nina Scholz 's answer in a function
objectReplacer(arrayOfObjects, newObject) {
let index = arrayOfObjects.findIndex((value) => value === newObject.value);
if (index === -1) {
arrayOfObjects.push(newObject);
} else {
arrayOfObjects[index] = newObject;
}
}
var index = items.indexOf(3452);
if (index !== -1) {
items[index] = 1010;
}
Also it is recommend you not use the constructor method to initialize your arrays. Instead, use the literal syntax:
var items = [523, 3452, 334, 31, 5346];
You can also use the ~ operator if you are into terse JavaScript and want to shorten the -1 comparison:
var index = items.indexOf(3452);
if (~index) {
items[index] = 1010;
}
Sometimes I even like to write a contains function to abstract this check and make it easier to understand what's going on. What's awesome is this works on arrays and strings both:
var contains = function (haystack, needle) {
return !!~haystack.indexOf(needle);
};
// can be used like so now:
if (contains(items, 3452)) {
// do something else...
}
Starting with ES6/ES2015 for strings, and proposed for ES2016 for arrays, you can more easily determine if a source contains another value:
if (haystack.includes(needle)) {
// do your thing
}
The Array.indexOf() method will replace the first instance. To get every instance use Array.map():
a = a.map(item => item == 3452 ? 1010 : item);
Of course, that creates a new array. If you want to do it in place, use Array.forEach():
a.forEach((item, i) => { if (item == 3452) a[i] = 1010; });
Instead of finding the index and filtering you could always use .map to return a new array.
const myObj = { id: 2, new: 1 };
const myArr = [{ id: 1 }, { id: 2 }, { id: 3 }];
const newArr = myArr.map(v => {
return v.id === myObj.id ? myObj : v;
});
It depends on what you would like to do if the item is not found in the array, as this will only replace.
By better if you mean faster method, here is one,
for(let i = 0;i<myArr.length; i++) {
if(myArr[i].id === myObj.id) {
myArr[i] = myObj;
break;
}
}
This is faster than your method because we are using for loop instead of .filter() or .findIndex() which is slower than regular for loop.
If you mean the most compact then you can do this,
myArr[myArr.findIndex(item => item.id === myObj.id)] = myObj;
Note that this approach will fail if there is no item with the given object key.
You can use Array#find.
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);
You could use Array.reduce to copy the array with the new devices disabled:
const devices = [ /* ... */ ];
const newDevices = devices.reduce((ds, d) => {
let newD = d;
if (d.deviceID === 'eI2K-6iUvVw:APA') {
newD = Object.assign({}, d, { enabled: false });
}
return ds.concat(newD);
}, []);