Merge two dynamic object arrays: Merge two dynamic object arrays into one
<p>I have a dynamic array of two objects as shown below (this is a dynamic array of n objects): </p>
<pre class="brush:php;toolbar:false;">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},
]</pre>
<p>I merged the two arrays into an object with the same ID like this: </p>
<pre class="brush:php;toolbar:false;">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
}
}
}
}</pre>
<p>However, I also want to include in the final <code>serverArray</code> those IDs that are not in <code>serverArray</code> (i.e. <code>field5</ in the example above code>, <code>field6</code>), and these fields will also fail the above condition (i.e. <code>serverArray[x].id == localArray[y].id</code>), I hope These fields are also included as part of the final <code>serverArray</code>, i.e. my final <code>serverArray</code> should also contain the following two objects: </p>
<pre class="brush:php;toolbar:false;">{"id":"field5","mandatory":false,"visible":true},
{"id":"field6","mandatory":true,"visible":false},</pre>
<p>Is there any way to achieve this requirement? </p>