Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

97
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda