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

244
Visualizações
What does this Object.assign({}, ...array.map(/*...*/)) code do here

I have cloned this repo from github and I am unable to understand what's happening in the code.

words in the code is an array of words.

const wordDictionary = Object.assign({}, ...words.map((x) => ({ [x]: x })));
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

It's taking an array (of strings, since you said it's an array of words; but it would work with numbers or Symbols too) and converting it to an object where both the names and values of the properties are the same. So for example, ["an", "example"] becomes {an: "an", example: "example"}:

const words = ["an", "example"];
const wordDictionary = Object.assign({}, ...words.map((x) => ({ [x]: x })));
console.log(wordDictionary);

It does it by mapping each array element to an object with one property (named by the array element, with the value of the array element) and then assigning all of those objects to a single target object.

For instance, with my ["an", "example"] array, the steps are:

  1. Do the mapping, turning:
    ["an", "example"]
    
    into
    [{an: "an"}, {example: "example"}]
    
  2. Spread that array out into discrete arguments to Object.assign with a blank target object. So
    Object.assign({}, ...[{an: "an"}, {example: "example"}])
    
    becomes
    Object.assign({}, {an: "an"}, {example: "example"})
    
  3. Use Object.assign to assign the properties from those objects to the first one (the blank {} object).

It's worth noting that the code is overcomplicated. It would be much simpler just to use a loop:

const wordDictionary = {};
for (const word of words) {
    wordDictionary[word] = word;
}

Separately, dictionaries like this are better handled by Map instances:

const wordDictionary = new Map();
for (const word of words) {
    wordDictionary.set(word, word);
}

or in this specific case (since the key and value are the same) a Set:

const wordDictionary = new Set(words);
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