0π
β
It may not be the best solution but give it a try.
let arr1 = [{
"id": 1,
"date": "2019-03-27",
"time": 1,
"max_tasks": 3,
"reservations": [
5,
2
]
},
{
"id": 2,
"date": "2019-03-28",
"time": 1,
"max_tasks": 3,
"reservations": []
},
{
"id": 3,
"date": "2019-03-29",
"time": 1,
"max_tasks": 3,
"reservations": []
},
{
"id": 4,
"date": "2019-03-30",
"time": 1,
"max_tasks": 3,
"reservations": []
},
{
"id": 5,
"date": "2019-03-31",
"time": 1,
"max_tasks": 3,
"reservations": []
},
{
"id": 6,
"date": "2019-04-01",
"time": 1,
"max_tasks": 3,
"reservations": []
},
{
"id": 7,
"date": "2019-04-02",
"time": 1,
"max_tasks": 3,
"reservations": [
3
]
}
]
let arr2 = [{
"id": 5,
"app": 1,
"comment": "test 5"
},
{
"id": 2,
"app": 1,
"comment": "test 2"
}
]
arr1.forEach(o => {
let updatedReverations = []
o.reservations.forEach(r => {
updatedReverations.push(arr2.filter(a2 => r === a2.id)[0] || r)
})
o.reservations = updatedReverations
})
console.log(arr1)
0π
perhaps this works
var arr1 = [
{
"id": 1,
"date": "2019-03-27",
"time": 1,
"max_tasks": 3,
"reservations": [
5,
2
]
},
{
"id": 2,
"date": "2019-03-28",
"time": 1,
"max_tasks": 3,
"reservations": []
},
{
"id": 3,
"date": "2019-03-29",
"time": 1,
"max_tasks": 3,
"reservations": []
},
{
"id": 4,
"date": "2019-03-30",
"time": 1,
"max_tasks": 3,
"reservations": []
},
{
"id": 5,
"date": "2019-03-31",
"time": 1,
"max_tasks": 3,
"reservations": []
},
{
"id": 6,
"date": "2019-04-01",
"time": 1,
"max_tasks": 3,
"reservations": []
},
{
"id": 7,
"date": "2019-04-02",
"time": 1,
"max_tasks": 3,
"reservations": [
3
]
}
]
var arr2 = [
{
"id": 5,
"app": 1,
"comment": "test 5"
},
{
"id": 2,
"app": 1,
"comment": "test 2"
}
]
for (var i = 0; i != arr1.length; ++i) {
arr1[i].reservations = arr1[i].reservations.map(id => {
var reservation = arr2.find(reservation => reservation.id == id)
return reservation || id;
});
}
It will try to find reservation in array 2 if not it will not replace the id.
0π
below function will give you new copy of merged array.
function getMergedArray(arr1,arr2){
return arr1.map(item=>{
if(item.reservations.length>0){
let newReservations= item.reservations.map(reservationId=>{
let foundReservation = arr2.find(reservation=>{
return reservation.id === reservationId
})
if(foundReservation){
return foundReservation;
}
else{
return reservationId;
}
})
item.reservations = newReservations;
}
return item;
});
}
Source:stackexchange.com