2

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.

1
  • First off you can't access Map properties using bracket notation you need to use the set and get methods. Perhaps you meant to use an object? Commented Oct 20, 2021 at 21:58

1 Answer 1

2

You can use Array#reduce to get the nested Map, after which you can set the 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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.