搜索

首页  >  问答  >  正文

合并两个动态对象数组:将两个动态对象数组合并为一个

<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>
P粉903969231P粉903969231465 天前480

全部回复(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
  • 取消回复