Skip to content
Advertisement

JavaScript lookup: update value of object in array if object key exists in another object array similar to the v-lookup in excel

Just trying to update the dates in array2 if ID matches in array1 so that they are not null.

let array1 = [{"id":1, "date": "23/11/21"}, {"id":2, "date":"20/11/21"}, {"id":3, "date":"15/11/21"}]

let array2 = [{"id":1, "name": "John", "date": null}, {"id":2, "name": "Max", "date": null}, {"id":3, "name": "Peter", "date": null}]

Desired output:

let array2 = [{"id":1, "name": "John", "date":"23/11/21" }, {"id":2, "name": "Max", "date": "20/11/21"}, {"id":3, "name": "Peter", "date": "15/11/21"}]

How do I use a loop with the indexof() method?

Advertisement

Answer

You could use a map method to iterate trough the second array, find an element with the same id in the first array and take the date from there:

let array1 = [{
  "id": 1,
  "date": "23/11/21"
}, {
  "id": 2,
  "date": "20/11/21"
}, {
  "id": 3,
  "date": "22/11/15"
}]

let array2 = [{
  "id": 1,
  "name": "John",
  "date": null
}, {
  "id": 2,
  "name": "Max",
  "date": null
}, {
  "id": 3,
  "name": "Peter",
  "date": null
}];

const updated = array2.map(el => {
  const isIdInFirstArr = array1.find(e => e.id === el.id);
  if (isIdInFirstArr) {
    el.date = isIdInFirstArr.date;
  }
  return el;
})

console.log(updated)
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement