I have a problem to create an object list based from existing array.
Given I have an empty object:
let data = {}
which I would like to populate from an existing array:
const list = ['somedata1', 'somedata2', 'somedata3']
I want to make a following object list based from provided array:
data = {
somedata1: undefined,
somedata2: [],
somedata3: 0
}
So I cant access either access or reassign them like so:
// Access
data.somedata1;
// Set new value
data.somedata2 = {subObject: true}
I've tried different approaches with Object.assign, Object.fromEntries, and this one which does not solve the problem:
list.forEach(i => {
data[i] = undefined
})
And I expect to be the list such as:
data {
somedata1: undefined,
somedata2: undefined,
somedata3: undefined
}
So I could reassign them like so:
data.somedata1 = 1100
data.somedata2 = ['somevalues']
data.somedata3 = false
==== UPDATE ====
So to make it work, I had to RETURN an assignment, instead of only ASSIGNING the object. I don't get it why it's like that, if someone could explain it will be perfect.
// WORKING: This function is return an assignment
list.forEach(item => data[item] = undefined)
// WORKING: This arrow function returns an assignment
list.forEach(item => {
return data[item] = undefined
})
// NON-WORKING: This arrow function only assigns without RETURNing the value
list.forEach(item => {
data[item] = undefined
})
list.forEachsolution appears to work. Are you not getting the expected result?list.forEachapproach, it works.keyinstead ofk