I am trying to generate a map of the following format dynamically based on user inputs:
{
Jane: {
Comments: ["Hello", "Hi"]
},
John: {
Age: "999",
Comments: "Hi"
}
}
The keys, the values and the nests are all in runtime - so initially all I will know is that the top-level structure is a map. I attempted to make this at runtime using the below code.
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);
However, it overwrites the value of Comments instead of making it as arrays.
Can someone please help me with creating this non-overwriting nested map with array values? (Note: any other values except comments are not arrays)
Thanks in advance.
setandgetmethods. Perhaps you meant to use an object?