I have 2 arrays, I'd like to combine them if they have the same two object keys.
If no match is found, still keep the object, but have the value as 0.
Example of Input
withdrawal: [
{
"id": "a1",
"withdrawalAmount": 300,
"user": "John"
},
{
"id": "b2",
"withdrawalAmount": 100,
"user": "Mike"
}
{
"id": "c3",
"withdrawalAmount": 33,
"user": "John"
}
]
deposit: [
{
"id": "a1",
"depositAmount": 123,
"user": "John"
},
{
"id": "c3",
"depositAmount": 44,
"user": "John"
},
]
Expected Output
transactions: [
{
"id": "a1",
"depositAmount": 123,
"withdrawalAmount": 300,
"user": "John"
},
{
"id": "b2",
"depositAmount": 0,
"withdrawalAmount": 100,
"user": "Mike"
},
{
"id": "c3",
"depositAmount": 44,
"withdrawalAmount": 33
"user": "John"
},
]
This is the function I tried so far, but it doesn't work due the two input arrays being a different length.
function mergeArrayObjects(arr1, arr2) {
return arr1.map((item, i) => {
if (item.user === arr2[i].user) {
//merging two objects
return Object.assign({}, item, arr2[i])
}
})
}
arr2if those do not have a matchingidinarr1. So, if thearr2array had an element like:{"id" : "c3", "depositAmount": 333, "user": "tom"}andarr1did not have a correspondingc3element, then this deposit will be excluded from transactions. May be this is what is needed? Please update the question to clarify.depositforid = 'c3', but there is no entry inwithdrawalforid = 'c3'? Should there be an entry intransactionswithwithdrawalAmount = 0?