如何在JavaScript函数中对比对象数组URL并按条件迁移指定字段?
解决方案
要实现这个需求,我们可以通过构建URL映射表来高效匹配昨日数据,同时处理好异步操作的逻辑。这里是完整的实现:
步骤说明
- 先将数据库返回的昨日图表数据转换成以
URL为键的对象,这样后续匹配时可以做到O(1)的查找效率,避免多次遍历数组。 - 遍历传入的
jsonObj数组,对每个条目查找映射表中的对应数据:- 找到匹配项时,将昨日的
Position赋值为PreviousPosition,同时沿用昨日的CustomKey - 无匹配时,将
PreviousPosition和CustomKey设为null
- 找到匹配项时,将昨日的
- 注意异步操作的处理:因为
dbService.getDate是异步方法,我们可以用async/await让代码逻辑更清晰易读。
完整代码
const syncWithPreviousDay = async (jsonObj) => { // 先获取昨日的图表数据 const result = await dbService.getDate(config.yesterday); // 构建URL到昨日数据的映射表 const yesterdayChartMap = result.chart.reduce((map, item) => { map[item.URL] = { PreviousPosition: item.Position, CustomKey: item.CustomKey }; return map; }, {}); // 处理当前图表数据,添加PreviousPosition和CustomKey字段 const processedChart = jsonObj.map(item => { const matchedData = yesterdayChartMap[item.URL]; return { ...item, PreviousPosition: matchedData ? matchedData.PreviousPosition : null, CustomKey: matchedData ? matchedData.CustomKey : null }; }); // 组装最终的data对象 const data = { date: config.dateToday, chart: processedChart }; return data; };
验证结果
用你提供的测试数据运行后,data.chart会生成完全符合你期望的结构:
[
{ "Position": "1", "TrackName": "Rocket", "URL": "https://domain.local/nbs678", "PreviousPosition": null, "CustomKey": null },
{ "Position": "2", "TrackName": "Dueling banjos", "URL": "https://domain.local/asd456", "PreviousPosition": "3", "CustomKey": null },
{ "Position": "3", "TrackName": "One hit wonder", "URL": "https://domain.local/xyz123", "PreviousPosition": "1", "CustomKey": "x" }
]
补充说明
如果你的项目环境还不支持async/await,也可以用.then()链式调用的方式实现,逻辑是完全一致的:
const syncWithPreviousDay = (jsonObj) => { return dbService.getDate(config.yesterday) .then(result => { const yesterdayChartMap = result.chart.reduce((map, item) => { map[item.URL] = { PreviousPosition: item.Position, CustomKey: item.CustomKey }; return map; }, {}); const processedChart = jsonObj.map(item => { const matchedData = yesterdayChartMap[item.URL]; return { ...item, PreviousPosition: matchedData ? matchedData.PreviousPosition : null, CustomKey: matchedData ? matchedData.CustomKey : null }; }); return { date: config.dateToday, chart: processedChart }; }); };
内容的提问来源于stack exchange,提问作者Dave
相关产品推荐
相关产品推荐

