搜尋

首頁  >  問答  >  主體

合併兩個動態物件數組:將兩個動態物件數組合併為一個

<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>中的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>
P粉903969231P粉903969231465 天前481

全部回覆(1)我來回復

  • P粉330232096

    P粉3302320962023-08-19 13:04:50

    在循環遍歷兩個陣列時,您可以建立一個新物件來追蹤合併的欄位。在初始合併之後,您可以再次遍歷localArray,以識別尚未合併到serverArray中的字段,並將它們添加到合併結果中。

    let mergedFields = {};
    
    // 根据共同的ID进行初始合并
    for (let y = 0; y < localArray.length; y++) {
        const localField = localArray[y];
        const serverField = serverArray.find(field => field.id === localField.id);
    
        if (serverField) {
            mergedFields[localField.id] = {
                ...serverField,
                ...localField
            };
        } else {
            mergedFields[localField.id] = localField;
        }
    }
    
    // 添加在mergedFields中不存在的剩余localArray字段
    for (let y = 0; y < localArray.length; y++) {
        const localField = localArray[y];
        if (!mergedFields.hasOwnProperty(localField.id)) {
            mergedFields[localField.id] = localField;
        }
    }
    
    // 将mergedFields对象转换回数组
    const mergedServerArray = Object.values(mergedFields);
    
    console.log(mergedServerArray);

    回覆
    0
  • 取消回覆