2

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
})

9
  • Your list.forEach solution appears to work. Are you not getting the expected result? Commented Sep 6, 2019 at 15:19
  • What's wrong with your list.forEach approach, it works. Commented Sep 6, 2019 at 15:20
  • Yes i have tested with forEach it is working fine. Commented Sep 6, 2019 at 15:20
  • 1
    list.forEach(item=>data[item]=undefined)..This is only required.I don't know what is the problem then. Commented Sep 6, 2019 at 15:21
  • 1
    In your comment above you're referencing key instead of k Commented Sep 6, 2019 at 15:27

1 Answer 1

1

If you want to convert the values of an array to be the keys of another object (with their values as undefined, that you can do it in multiple ways):

here are two examples

const list = ['somedata1', 'somedata2', 'somedata3']

// imperative code
const data = {};
list.forEach(elm => {
    data[elm] = undefined;
})

// or

// functional code
const newData = list.reduce((acc, cur) => ({...acc, [cur] : undefined}), {})
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.