Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
175
rated 0 times [  177] [ 2]  / answers: 1 / hits: 19708  / 5 Years ago, mon, february 25, 2019, 12:00:00

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 correct object into the array?



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'
}
]


What I tried so far:



for(let i = 0; i < allItems.length; i++) {
if(newItems.indexOf(allItems[i].id) > -1){
allItems[i] = newItems
}
}


How can I get the position of the object in newItems and then replace it into allItems?


More From » arrays

 Answers
14

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.


[#52536] Thursday, February 21, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brianaclaras

Total Points: 23
Total Questions: 106
Total Answers: 111

Location: Japan
Member since Sat, Jun 6, 2020
4 Years ago
;