javascript - 基于特定对象之间的对象 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 }
]
解决方案
请使用此代码。
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);
推荐阅读
- javascript - 如何在 javascript 中为 com、com.*、co、co.* 构建正则表达式
- c# - 如何在列表框或其他内容中显示排序列表的键 n 值?C#
- python - 如何从显示的熊猫数据框中读取选定的行作为 ipywidgets 中的输出
- json - 包含具有特定条目的 JSON 数组的对象的 JSON 路径
- javascript - 在 redux store 更新后调用函数
- javascript - 使用带有 Javascript RegExp 构造函数的正则表达式
- aws-lambda - 如何为自包含的 lambda@edge 函数创建没有源的 CloudFront 分配?
- python - 计算前 7 天熊猫系列的总计数和价值总和
- prometheus - 如何查询空时间范围之间的增量变化
- ansible - Ansible 新用户更改 ansible tmp 目录