JavaScript如何按键名序号匹配两对象合并为指定对象数组
实现方案
不需要把两个对象全量拆成独立数组再做交叉匹配,直接以配料对象为遍历基准,提取键名序号映射对应度量值即可,逻辑更短、性能更高,还能自动处理度量值缺失的场景,同时自动清理原始值首尾的多余空格。
核心实现代码如下:
// 原始入参 const ingredientObj = { strIngredient1: 'Light rum', strIngredient2: 'Lime', strIngredient3: 'Sugar', strIngredient4: 'Mint', strIngredient5: 'Soda water' } const measureObj = { strMeasure1: '2-3 oz ', strMeasure2: 'Juice of 1 ', strMeasure3: '2 tsp ', strMeasure4: '2-4 ' } const res = Object.entries(ingredientObj).map(([key, ingredient]) => { // 提取键名中的数字序号 const serialNum = key.slice('strIngredient'.length) // 匹配对应度量值,不存在则返回空字符串,同时去除首尾多余空格 const measure = (measureObj[`strMeasure${serialNum}`] || '').trim() return { ingredient, measure } })
运行后输出结果完全匹配预期结构:
[ { ingredient: 'Light rum', measure: '2-3 oz' }, { ingredient: 'Lime', measure: 'Juice of 1' }, { ingredient: 'Sugar', measure: '2 tsp' }, { ingredient: 'Mint', measure: '2-4' }, { ingredient: 'Soda water', measure: '' } ]
逻辑说明
- 以配料对象为唯一遍历源,避免双数组遍历的额外开销,时间复杂度为O(n)
- 因为键名前缀固定,直接用
slice截掉固定前缀取序号,比正则匹配性能更好、写法更简单 - 用
|| ''做兜底处理,没有对应度量值时自动填空字符串 - 统一用
trim()清理原始值首尾的多余空格,和示例输出的格式对齐 - 如果运行环境支持ES2020+的可选链、空值合并运算符,度量值那行也可以写成
const measure = measureObj[strMeasure${serialNum}]?.trim() ?? '',逻辑等价。
内容的提问来源于stack exchange,提问作者Sean
相关产品推荐
相关产品推荐

