'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;
}
}
Solution 1:[1]
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.
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | lolBOT V9.17 |
| Solution 2 |
