简体   繁体   English

如何从字符串数组创建对象映射?

[英]How can I create an object mapping from an array of strings?

i am stumbling onto something that should be easy, yet i can't seem to be able to do it.我偶然发现了一些应该很容易的事情,但我似乎无法做到。

i have an array of string, and i want to map over it to create an object like so :我有一个字符串数组,我想映射它以创建一个像这样的对象:

const monthesList = ['january', 'february', 'march', 'april', 'may']

const myState = monthesList.map(month => (
    month: {selected: false, year: 2022}
    )
  )

what i want is to get the following object :我想要的是获得以下对象:

myState ={
  january:{ 
    selected: false,
    year: 2022
  },
  february:{ 
    selected: false,
    year: 2022
  },
  march:{ 
    selected: false,
    year: 2022
  },
  april:{ 
    selected: false,
    year: 2022
  },
  may:{ 
    selected: false,
    year: 2022
  },
}

Edit: i just found the way :编辑:我刚刚找到了方法:

const myState = monthesList.map(month => (
    {[month] : {
      selected: false,
      year: 2022
    }}
    )
  )

just need to make an object out of it, shouldn't be too hard只需要用它做一个对象,不应该太难

The .map() method returns an array, but the output that you're after is an object. .map()方法返回一个数组,但您所追求的输出是一个对象。 You need something that can convert an array of key-value pairs (ie: [key, value] ) to an object.您需要一些可以将键值对数组(即: [key, value] )转换为对象的东西。 For this, we have the Object.fromEntries() method that takes an array of key-value pairs, and from it, constructs an object like so:为此,我们有Object.fromEntries()方法,它接受一个键值对数组,并从中构造一个对象,如下所示:

 const monthesList = ['january', 'february', 'march', 'april', 'may']; const myState = Object.fromEntries(monthesList.map(month => [ month, {selected: false, year: 2022} ])); console.log(myState);

You can use map to generate an array of arrays with the values in each internal array being the month name and object;您可以使用map生成一个数组数组,其中每个内部数组中的值是月份名称和对象; then use Object.fromEntries to convert that into your desired object:然后使用Object.fromEntries将其转换为您想要的对象:

 const monthesList = ['january', 'february', 'march', 'april', 'may'] const myState = Object.fromEntries( monthesList.map(m => [m, {selected: false, year: 2022}]) ) console.log(myState)

map will only return an array. map只会返回一个数组。 Your expected output is an object.您的预期输出是一个对象。 There's no need to over-complicate things - use a simple loop instead.没有必要让事情变得过于复杂——改用一个简单的循环

 const list = ['january', 'february', 'march', 'april', 'may']; const myState = {}; for (const month of list) { myState[month] = { selected: false, year: 2022 }; } console.log(myState);

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

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