如何基于storeId键值匹配合并两个API返回的对象数组
问题原因
你原代码存在以下几个核心错误:
- 数组元素访问错误:
logistics和stores都是数组,需要通过下标logistics[i]、stores[k]获取对应位置的对象,直接写logistics.storeId无法读取到正确值 - 展开运算符使用错误:你尝试对字符串类型的
stores.name、logistics.logisticsId做展开,会把字符串拆分为单个字符的键值对,完全不符合需求,应该直接展开整个对象 - 存在语法错误:代码中有多余的闭合大括号、重复声明变量
d、脱离对象的独立属性行等问题 - 双重循环效率较低:当两个数组数据量较大时,嵌套循环时间复杂度为O(n*m),性能较差
最优解决方案
推荐先把stores数组转换为以storeId为键的Map,再遍历logistics数组匹配合并,时间复杂度为O(n+m),性能更好:
// 1. 把stores转成Map,key为storeId,value为对应的门店对象 const storeMap = new Map(stores.map(store => [store.storeId, store])) // 2. 遍历logistics匹配合并 const mergedList = logistics.map(logi => { const matchedStore = storeMap.get(logi.storeId) // 匹配到就合并,没匹配到就只返回物流信息(可根据需求调整) return matchedStore ? {...matchedStore, ...logi} : logi }) console.log(mergedList) // 如果只要第一个匹配的对象,直接取mergedList[0]即可
如果两个数组的storeId有重名字段,后面展开的对象会覆盖前面的,你可以根据需求调整...matchedStore和...logi的顺序。
原双重循环修改版
如果你要保留原来的嵌套循环写法,修改后代码如下:
const logistics = [{ logisticsId: "L5E69E26D8FCAE", storeId: 409388, logisticsDate: "2020-03-12T07:19:09.000Z", }]; const stores = [{ storeId: 409388, ka: 0, country: "ru", name: "test", city: "Moscow", cxw: 1, cx: 1, plz: 22448, }]; const mergedList = []; for (let i = 0; i < logistics.length; ++i) { const currentLogi = logistics[i]; for (let k = 0; k < stores.length; ++k) { const currentStore = stores[k]; if (currentLogi.storeId === currentStore.storeId) { // 合并两个对象 const merged = {...currentStore, ...currentLogi}; mergedList.push(merged); } } } console.log(mergedList);
内容的提问来源于stack exchange,提问作者GoOsT
相关产品推荐
相关产品推荐

