Just trying to update the dates in array2 if ID matches in array1 so that they are not null.
JavaScript
x
5
1
let array1 = [{"id":1, "date": "23/11/21"}, {"id":2, "date":"20/11/21"}, {"id":3, "date":"15/11/21"}]
2
3
let array2 = [{"id":1, "name": "John", "date": null}, {"id":2, "name": "Max", "date": null}, {"id":3, "name": "Peter", "date": null}]
4
5
Desired output:
JavaScript
1
3
1
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"}]
2
3
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:
JavaScript
1
34
34
1
let array1 = [{
2
"id": 1,
3
"date": "23/11/21"
4
}, {
5
"id": 2,
6
"date": "20/11/21"
7
}, {
8
"id": 3,
9
"date": "22/11/15"
10
}]
11
12
let array2 = [{
13
"id": 1,
14
"name": "John",
15
"date": null
16
}, {
17
"id": 2,
18
"name": "Max",
19
"date": null
20
}, {
21
"id": 3,
22
"name": "Peter",
23
"date": null
24
}];
25
26
const updated = array2.map(el => {
27
const isIdInFirstArr = array1.find(e => e.id === el.id);
28
if (isIdInFirstArr) {
29
el.date = isIdInFirstArr.date;
30
}
31
return el;
32
})
33
34
console.log(updated)