首页 > 解决方案 > 基于特定对象之间的对象 ID 序列的数组连接

问题描述

我有两个不同的数组,如果对象 id 之间有可用的对象,我想将第二个数组中的数组对象添加到最终数组中。

firstArray = [
    { id: 'LOA13', type: 'LOAD', otherProperty: 11 },
    { id: 'UNA1', type: 'UNLOAD', otherProperty: 22 },
    { id: 'LOA14', type: 'LOAD', otherProperty: 33 },
    { id: 'UNA15', type: 'UNLOAD', otherProperty: 44 }
]

secondArray = [
    { id: 'LOA13', type: 'LOAD', otherProperty: 12 },
    { id: '123', type: 'DRAG', otherProperty: 34 }, 
    { id: 'UNA1', type: 'UNLOAD', otherProperty: 56 },
    { id: 'LOA14', type: 'LOAD', otherProperty: 12 },
    { id: '456', type: 'DRAG', otherProperty: 1212 },
    { id: '789', type: 'DRAG', otherProperty: 9898 },   
    { id: 'UNA15', type: 'UNLOAD', otherProperty: 56 }
]

如果在特定 Ids 序列之间找到任何对象,则它们应添加到数组中的结果中。

预期的结果是这样的:

[
    { id: 'LOA13', type: 'LOAD', otherProperty: 11 }, 
    { id: '123', type: 'DRAG', otherProperty: 34 }, // ADDED as found between ID= LOA13 and UNA1
    { id: 'UNA1', type: 'UNLOAD', otherProperty: 22 }, 
    { id: 'LOA14', type: 'LOAD', otherProperty: 33 },
    { id: '456', type: 'DRAG', otherProperty: 1212 }, // ADDED as found between ID=LOA14 and UNA15
    { id: '789', type: 'DRAG', otherProperty: 9898 }, // ADDED as found between ID=LOA14 and UNA15  
    { id: 'UNA15', type: 'UNLOAD', otherProperty: 44 }
]

标签: javascriptarraystypescript

解决方案


请使用此代码。

const resultArray = secondArray.map((val, index) => {
    if(firstArray.filter(value => value.id == val.id).length == 0) {
        let pos = index - 1;
        while(firstArray.filter(value => value.id == secondArray[pos].id).length == 0) pos--;
        const betweenIndex = firstArray.indexOf(firstArray.filter(value => value.id == secondArray[pos].id)[0]);
        const result = "ADDED as found between ID= " + firstArray[betweenIndex].id + " and " + firstArray[betweenIndex+1].id;
        return {...val, result};
    }
    return val;
});
console.log(resultArray);

推荐阅读