Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and replace object in array (based on id)

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?

like image 246
jj008 Avatar asked Feb 25 '19 23:02

jj008


People also ask

How do I find the ID of an array of objects?

Overview. In JavaScript, we can use the Array. prototype. find() method to find an object by ID in an array of objects.

How do you replace an element in an array by index?

To replace an element in an array:Use the indexOf() method to get the index of the element you want to replace. Call the Array. splice() method to replace the element at the specific index. The array element will get replaced in place.


2 Answers

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.

like image 103
jo_va Avatar answered Oct 12 '22 13:10

jo_va


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);
like image 22
Jack Bashford Avatar answered Oct 12 '22 13:10

Jack Bashford