Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

98
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda