I have two dynamic arrays of objects as below (this is a dynamic array of n objects):
serverArray = [
{"id":"field1","mandatory":false,"visible":false},
{"id":"field2","mandatory":false,"visible":false},
{"id":"field3","mandatory":false,"visible":false},
{"id":"field4","mandatory":false,"visible":false}
]
localArray = [
{"id":"field1"},
{"id":"field2","mandatory":false},
{"id":"field3","mandatory":true,"visible":false},
{"id":"field4","mandatory":false,"visible":true},
{"id":"field5","mandatory":false,"visible":true},
{"id":"field6","mandatory":true,"visible":false},
]
I merge these 2 arrays for the ones with common IDs as below:
for (let x = 0; x < serverArray.length; x++) {
for (let y = 0; y < localArray.length; y++) {
if (serverArray[x].id == localArray[y].id) { // serverArray[x].id/localArray[y].id = 'field1', 'field2'
for (let key in localArray[y]) { //key = 'id', 'mandatory', etc
serverArray[x][key] = localArray[y].hasOwnProperty(key) ? localArray[y][key] : serverArray[x][key]; //Override with local field attribute value (if present) in final returned response
}
}
}
}
However, what I also want is for the IDs which are not present in serverArray
(i.e. field5
, field6
in the above example) and which would fail the above condition (i.e. serverArray[x].id == localArray[y].id
), I want these fields also as part of my final serverArray
, i.e. in my final serverArray
it should also have the below 2 objects:
{"id":"field5","mandatory":false,"visible":true},
{"id":"field6","mandatory":true,"visible":false},
Is there a way to achieve the same?
2
Answers
You can create a new object to keep track of merged fields while looping through both arrays. After the initial merge, you can loop through the localArray again to identify fields that are not yet merged into the serverArray and add them to the merged result.
Instead of using iteration to find a match by id, first create a dictionary so you can access the server objects by their id in O(1) time.
Secondly, the inner loop over the keys can be replaced by a call to
Object.assign
.To add missing objects, first check in the above dictionary if the key didn’t occur yet, and then push the local object to the server array: