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

140
Visualizações
How to dynamically assign properties and values to an object in Javascript

I am trying to assign properties and values to an object initialized as empty. However, it keeps on prompting the Error: Cannot assign properties of undefined (setting '0' ). Note "duplicate" is a copy of the text gotten using the map method in some code lines above.

I am using a for loop for this assignment. The code snippet is shown below.

 //Initialise an object to hold array data
    const dataStore = {};
 //Note: text is an array of string

    for (let i = 0; i < text.length; i++)
    {
        let dataStoreKeyCounter = 0;
        if ((Object.hasOwn(dataStore, text[i])) !== true)
        {
            for (let j = 0; j < duplicate.length; j++)
            {
                if (text[i] == duplicate[j])
                {
                    dataStoreKeyCounter++;
                }
            }
            //Set the text as the a property and the counter as its value.
            dataStore.text[i] = dataStoreKeyCounter;
        }
        
    }





about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

In your code, you put dataStore.text[i]. You have not declared dataStore.text. After declaring your object, do dataStore.text = {}

Also, make sure your duplicate is created by

let duplicate = {...dataStore}

This way, an edit to the original or the duplicate will not affect the other.

about 4 years ago · Juan Pablo Isaza Relatório

0

You can change the following line:

dataStore.text[i] = dataStoreKeyCounter;

To this:

dataStore[text[i]] = dataStoreKeyCounter;

This will first evaluate the value of text[i] and then pass it into dataStore as the key giving you the "dynamic" nature you are looking for.

The difference here is that when you access like this dataStore[key], if the key is not present in the Object, it is created.

Whereas, if you access dataStore.key, if key is not present, it will return undefined

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