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

139
Views
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 answers
Answer question

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 Report

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 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!