Home > Mobile >  JavaScript lookup: update value of object in array if object key exists in another object array simi
JavaScript lookup: update value of object in array if object key exists in another object array simi

Time:11-24

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?

CodePudding user response:

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)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

1) You can efficiently achieve this using Map as:

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 },
];

const map = new Map();
array1.forEach((o) => map.set(o.id, o.date));

let result = array2.map((o) => ({ ...o, date: o.date ?? map.get(o.id) }));
console.log(result);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

2) You can easily achieve the result using map and find

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 },
];

let result = array2.map(o => ({ ...o, date: o.date ?? array1.find(obj => obj.id === o.id)?.date}));
console.log(result)
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related