Merge two dynamic object arrays: Merge two dynamic object arrays into one
P粉903969231
2023-08-18 14:53:48
<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>
When looping through the two arrays, you can create a new object to keep track of the merged fields. After the initial merge, you can iterate over the localArray again to identify fields that have not yet been merged into the serverArray and add them to the merged result.