合并两个动态对象数组:将两个动态对象数组合并为一个
<p>我有两个对象的动态数组,如下所示(这是一个包含n个对象的动态数组):</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>我将这两个数组合并为具有相同ID的对象,如下所示:</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>然而,我还希望在最终的<code>serverArray</code>中包含那些不在<code>serverArray</code>中的ID(即上面示例中的<code>field5</code>,<code>field6</code>),并且这些字段也会失败上述条件(即<code>serverArray[x].id == localArray[y].id</code>),我希望这些字段也作为最终<code>serverArray</code>的一部分,即在我的最终<code>serverArray</code>中还应包含以下两个对象:</p>
<pre class="brush:php;toolbar:false;">{"id":"field5","mandatory":false,"visible":true},
{"id":"field6","mandatory":true,"visible":false},</pre>
<p>有没有办法实现这个要求?</p>