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 - Find and replace object in array (based on id) - Stack Overflow
javascript - How to find and replace an object with in array of objects - Stack Overflow
How do I replace all object values in an array with values from another array?
javascript - How can I find and update values in an array of objects? - Stack Overflow
Use Array.map and Array.find():
const allItems = [
{ 'id': 1, 'category_id': 1, 'text': 'old' },
{ 'id': 2, 'category_id': 1, 'text': 'old' }
];
const newItems = [
{ 'id': 1, 'category_id': 1, 'text': 'new', 'more_info': 'abcd' },
{ 'id': 2, 'category_id': 1, 'text': 'new', 'more_info': 'abcd' }
];
const result = allItems.map(x => {
const item = newItems.find(({ id }) => id === x.id);
return item ? item : x;
});
console.log(result);
This can even be shortened by using a logical or to return the original item when the call to find returns undefined:
const result = allItems.map(x => newItems.find(({ id }) => id === x.id) || x);
Regarding your code, you can't use indexOf since it only compares primitive values or references in the case of arrays and objects.
Just use map like so:
const allItems = [{
'id': 1,
'category_id': 1,
'text': 'old',
},
{
'id': 2,
'category_id': 1,
'text': 'old'
}
];
const newItems = [{
'id': 1,
'category_id': 1,
'text': 'new',
'more_info': 'abcd'
},
{
'id': 2,
'category_id': 1,
'text': 'new',
'more_info': 'abcd'
}
];
const replacedItems = allItems.map(e => {
if (newItems.some(({ id }) => id == e.id)) {
return newItems.find(({ id }) => id == e.id);
}
return e;
});
console.log(replacedItems);
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 );
Run code snippetEdit code snippet Hide Results Copy to answer Expand
- 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);
Run code snippetEdit code snippet Hide Results Copy to answer Expand
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 );
Run code snippetEdit code snippet Hide Results Copy to answer Expand
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!
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;
}
});
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.
Here's a solution using entries:
const arr = [
{
'before1': 1,
'same': 2,
'before2': 3
}, {
'before1': 4,
'same': 5,
}, {
'before1': 6,
'before2': 7
}, {
'same': 8,
'before2': 9
},
];
const keyReplacements = {
'before1': 'after1',
'same': 'same', // this is not necessary
'before2': 'after2'
};
const newArr = arr.map(obj =>
Object.fromEntries(Object.entries(obj).map(([k, v]) => [keyReplacements[k] || k, v]))
);
console.log(newArr);
Use ES6 map()
arrayObj = arrayObj.map(item => {
return {
value: item.key1,
key2: item.key2
};
});
Use findIndex() instead of find()
const index = array1.findIndex(o => o.id === 79);
if (index > -1) {
array1[index] = {randomProperty1: "lulu"};
}
BTW, shouldn't the new object have an id property?
One trick I have used when performance is top priority is to store the data in an object with an array of numeric ids to keep track of everything.
Example similar to yours:
var arr = [
{ id: 1, text: 'aaa' },
{ id: 2, text: 'bbb' },
{ id: 3, text: 'ccc' },
{ id: 78, text: 'zzz' }
];
var lookup = arr.reduce((prev, next) => {
prev[next.id] = next;
prev.allIds.push(next.id);
return prev;
}, { allIds: [] });
Now if you know the id you want to replace you don't need to loop at all
lookup[78] = { id: 78, text: 'new!' };
If you do want to loop through the array use the allIds property
lookup.allIds.forEach(x=> {
let item = lookup[x];
item.text = '';
});