简体   繁体   English

从数组向对象添加值

[英]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:我已经尝试了Object.assignObject.fromEntries不同方法,而这个并不能解决问题:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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