JavaScript动态构建嵌套Map时如何让Comments字段存数组不被覆盖
实现思路
- 针对最后一级键为
Comments的场景做特殊处理,实现值追加而非覆盖,其余字段保持直接赋值逻辑 - 修正原代码中Map实例和普通对象的操作混淆问题,顶层Map使用
get()/set()方法操作,内层普通对象使用属性访问符操作 - 处理
Comments字段的逻辑:首次赋值直接写入值,第二次及以后赋值自动转为数组存储多个值
修改后完整代码
var nest = function(map, keys, v) { // 复制keys数组避免修改原输入数组 const keysCopy = [...keys] if (keysCopy.length === 1) { const lastKey = keysCopy[0] // 特殊处理Comments字段 if (lastKey === 'Comments') { const existingVal = map instanceof Map ? map.get(lastKey) : map[lastKey] if (existingVal === undefined) { // 首次赋值直接写入 map instanceof Map ? map.set(lastKey, v) : map[lastKey] = v } else { // 已有值的情况转数组追加 const newVal = Array.isArray(existingVal) ? [...existingVal, v] : [existingVal, v] map instanceof Map ? map.set(lastKey, newVal) : map[lastKey] = newVal } } else { // 其他字段直接覆盖赋值 map instanceof Map ? map.set(lastKey, v) : map[lastKey] = v } } else { var key = keysCopy.shift(); let nextLevel = map instanceof Map ? map.get(key) : map[key] if (nextLevel === undefined) { nextLevel = {} map instanceof Map ? map.set(key, nextLevel) : map[key] = nextLevel } nest(nextLevel, keysCopy, v); } return map; }; var persons = new Map(); // Usage nest(persons, ['John', 'Comments'], 'Hi'); nest(persons, ['John', 'Age'], '999'); nest(persons, ['Jane', 'Comments'], 'Wow'); nest(persons, ['Jane', 'Comments'], 'Hello'); // 转换为普通对象打印查看结构 console.log(Object.fromEntries(persons));
运行输出结果
{ Jane: { Comments: ["Wow", "Hello"] }, John: { Age: "999", Comments: "Hi" } }
如果需要Comments字段无论多少个值都统一用数组存储,只需把首次赋值的逻辑改为[v]即可。
内容的提问来源于stack exchange,提问作者Tania
相关产品推荐
相关产品推荐

