I'm trying to dynamically update values inside a nested object like this :
mainObj = {
'Test 1': {
Nested1: 'value 1',
Nested2: 'value 2',
Nested3: 'value 3',
Nested4: 'value 4',
Nested5: 'value 5'
},
'Test 2': {
Nested1: 'value 1',
Nested2: 'value 2',
Nested3: 'value 3',
Nested4: 'value 4',
Nested5: 'value 5'
},
'Test 3': {
Nested1: 'value 1',
Nested2: 'value 2',
Nested3: 'value 3',
Nested4: 'value 4',
Nested5: 'value 5'
}
}
'Test X' and 'Nested X' are dynamic property names, I want to loop the object and try to update each 'value X' of each nested object.
But I always get the last iteration result for all 'Test X' object.
Here is my code :
for (const [key, value] of Object.entries(mainObj)) {
for (const [keyEm, valueEm] of Object.entries(mainObj[key])) {
const count = await dbquery(key, keyEm)
mainObj[key][keyEm] = count
}
}
Update
The mainObj I get it from another function (not direct initialization like the example). In my code :
const mainObj = await processObj()
like this even the Math.random() solution (in the answers) is not working, I always get the last nested object values in all nested objects.
Update 2
I can console log all values correctly with keys but I can't update it.
for (const x in mainObj) {
for (const y in mainObj[x]) {
const count = await dbquery()
console.log(`${x} ${y} ${count}`)
}
}
Like this I can see all the values correct : Test 1 - Nested 1 - Value from DB / Test 1 - Nested 2 - Value from DB etc...