我正在尝试根据用户输入动态生成以下格式的 map :
{
Jane: {
Comments: ["Hello", "Hi"]
},
John: {
Age: "999",
Comments: "Hi"
}
}
键、值和嵌套都在运行时 - 所以最初我只知道顶层结构是一个映射。我尝试使用下面的代码在运行时进行此操作。
var nest = function(map, keys, v) {
if (keys.length === 1) {
map[keys[0]] = v;
} else {
var key = keys.shift();
map[key] = nest(typeof map[key] === 'undefined' ? {} : map[key], keys, 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(persons);
但是,它会覆盖 Comments
的值,而不是将其设置为数组。
有人可以帮我创建这个带有数组值的非覆盖嵌套映射吗? (注意:除注释之外的任何其他值都不是数组)
提前致谢。
最佳答案
您可以使用Array#reduce
来获取嵌套的Map
,然后您可以设置key。
var nest = function(map, keys, v) {
const lastKey = keys.pop(), innerMap = keys.reduce((acc, key)=>{
if(!acc.has(key)) acc.set(key, new Map);
return map.get(key);
}, map);
if(lastKey !== 'Comments') innerMap.set(lastKey, v);
else {
if(!innerMap.has(lastKey)) innerMap.set(lastKey, []);
innerMap.get(lastKey).push(v);
}
};
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(persons); // Check browser console
关于Javascript用一些数组值动态初始化嵌套映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69653472/