Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

96
Views
Javascript dynamically initialize nested map with some array values

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!