简体   繁体   中英

Add values to object from an Array

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM