一只甜甜圈
您可以将对象存储在哈希表中,key并将另一个数组与哈希表中的数据合并。const array1 = [{ key: '5', value: '550' }, { key: '6', value: '750' }], array2 = [{ type: 'Job', status: 'Finished', key: '5' }, { type: 'Ticket', status: 'Processing', key: '6' }], temp = Object.fromEntries(array2.map(o => [o.key, o])), result = array1.map(o => ({ ...o, ...temp[o.key] }));console.log(result);.as-console-wrapper { max-height: 100% !important; top: 0; }
红糖糍粑
利用Array.prototype.map它可以将附加target对象传递给...,这里可以使用第二个数组,从中检索相应的合并项。合并是通过Object.assign将两个数组项合并到一个新创建的对象中来完成的,以便不改变任一涉及数组的任何合并项......const array1 = [{ key: '5', value: '550',}, { key: '6', value: '750',}];const array2 = [{ type: 'Job', status: 'Finished', key : '5',}, { type: 'Ticket', status: 'Processing', key : '6',}];function mergeWithSameIndexItemFromBoundArray(item, idx) { const boundArray = this; return Object.assign({}, item, boundArray[idx]);}console.log( 'merge result of array2 and array1 ...', array2.map(mergeWithSameIndexItemFromBoundArray, array1));console.log( 'merge result of array1 and array2 ...', array1.map(mergeWithSameIndexItemFromBoundArray, array2));.as-console-wrapper { min-height: 100%!important; top: 0; }如果存在不匹配的商品订单数组,可以基于上述方法向 提供额外的目标对象map。这次不是第二个数组,而是它的一个变换;一个对象,它使用标识所有项目的属性名称将第二个数组的所有项目映射到它。对于OP的示例,该属性名称是key。因此,需要编写一个附加函数来完成此映射任务。下面的下一个示例选择一种基于 的方法Array.prototype.reduce。此外,必须重写映射器函数,以便通过简单地使用数组项的key属性而不是之前的数组索引来利用之前创建的绑定映射...const array1 = [{ key: '5', value: '550',}, { key: '7', value: '320',}, { key: '6', value: '750',}];const array2 = [{ type: 'Ticket', status: 'Processing', key : '6',}, { type: 'Job', status: 'Finished', key : '5',}, { type: 'Task', status: 'Pending', key : '7',}];function createKeyBasedItemMap(map, item) { map[item.key] = item; return map;}function mergeWithKeyBasedItemFromBoundMap(item) { return Object.assign({}, item, this[item.key]);}console.log( 'map-based merge of unordered array2 and array1 items ...', array2.map( mergeWithKeyBasedItemFromBoundMap, array1.reduce(createKeyBasedItemMap, {}) ));console.log( 'map-based merge of unordered array1 and array2 items ...', array1.map( mergeWithKeyBasedItemFromBoundMap, array2.reduce(createKeyBasedItemMap, {}) ));console.log('\n');console.log( 'proof of concept ... the item-map based on array1 ...', array1.reduce(createKeyBasedItemMap, {}));console.log( 'proof of concept ... the item-map based on array2 ...', array2.reduce(createKeyBasedItemMap, {}));.as-console-wrapper { min-height: 100%!important; top: 0; }