Javascript 从数组创建对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42974735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:33:34  来源:igfitidea点击:

Create object from array

javascriptarraysecmascript-6javascript-objects

提问by Hussain Dehgamwala

I want to create object from list of array. I have an array which is dynamic which suppose to be look like this:

我想从数组列表中创建对象。我有一个动态数组,它看起来像这样:

var dynamicArray = ["2007", "2008", "2009", "2010"];

var dynamicArray = ["2007", "2008", "2009", "2010"];

and with some javascript es6 I want to make an object like this:

并使用一些 javascript es6 我想制作一个这样的对象:

const obj = {
    2007: {
        x: width / 5,
        y: height / 2
    },
    2008: {
        x: (2 / 5) * width,
        y: height / 2
    },
    2009: {
        x: (3 / 5) * width,
        y: height / 2
    },
    2010: {
        x: (4 / 5) * width,
        y: height / 2
    }
}

don't worry about inner objects but just wanted to a make structure like this:

不要担心内部对象,而只是想制作这样的结构:

 obj = {
      2007: ...,
      2008: ...,
      ...
    }

Please help, Thanks.

请帮忙,谢谢。

回答by georg

Simply

简单地

 const obj = {};

 for (const key of yourArray) {
      obj[key] = whatever;
 }

or if you prefer "functional" style:

或者如果您更喜欢“功能性”风格:

 const obj = yourArray.reduce((o, key) => Object.assign(o, {[key]: whatever}), {});

using the modern object spread operator:

使用现代对象扩展运算符:

const obj = yourArray.reduce((o, key) => ({ ...o, [key]: whatever}), {})

Example:

例子:

[
  { id: 10, color: "red" },
  { id: 20, color: "blue" },
  { id: 30, color: "green" }
].reduce((acc, cur) => ({ ...acc, [cur.color]: cur.id }), {})

Output:

输出:

{red: 10, blue: 20, green: 30}

Here is how it works:

下面是它的工作原理:

reduceis initialized with an empty object (empty {}at the end), therefore first iteration variables are acc = {}cur = { id: 10, color: "red" }. Function returns an object - this is why function body is wrapped in parentheses => ({ ... }). Spread operator doesn't do anything on the first iteration, so red: 10is set as first item.

reduce用一个空对象({}最后为空)初始化,因此第一个迭代变量是acc = {}cur = { id: 10, color: "red" }。函数返回一个对象——这就是函数体被括在括号中的原因=> ({ ... })。Spread 运算符在第一次迭代时不做任何事情,因此red: 10设置为第一项。

On the second iteration variables are acc = { red: 10 }cur = { id: 20, color: "blue" }. Here the spread operator expandsaccand the function returns { red: 10, blue: 20 }.

在第二次迭代变量是acc = { red: 10 }cur = { id: 20, color: "blue" }。此处展开运算符展开acc并且函数返回{ red: 10, blue: 20 }

Third iteration acc = { red: 10, blue: 20 }cur = { id: 30, color: "green" }, so when accis spread inside the object, our function returns the final value.

第三次迭代acc = { red: 10, blue: 20 }cur = { id: 30, color: "green" },所以当acc在对象内部传播时,我们的函数返回最终值。

回答by Abderrahmane TAHRI JOUTI

The new Object.fromEntries, from ECMAScript 2019, makes it even easier to transform values from an array into keys in an object like follows

Object.fromEntries来自 ECMAScript 2019的 new使将数组中的值转换为对象中的键变得更加容易,如下所示

const dynamicArray = ["2007", "2008", "2009", "2010"];
const obj = Object.fromEntries(
  dynamicArray.map(year => [year, {
    something: "based",
    on: year
  }])
)

console.log(obj)

回答by Ralexrdz

in js with es6 reduce function for array I do it like this

在 js 中使用 es6 减少数组函数我这样做

let x = [1,2,3]
let y = x.reduce((acc, elem) => {
  acc[elem] = elem // or what ever object you want inside
  return acc
}, {})
console.log(y) // {1:1, 2:2, 3:3}

回答by Alok Singh Mahor

var keys = ['key1', 'key2', 'key3']

var object = Object.assign({}, ...Object.entries({...keys}).map(([a,b]) => ({ [b]: 'someValue' })))
console.log(object)

This will produce

这将产生

{ key1: 'someValue', key2: 'someValue', key3: 'someValue' }

回答by jilykate

you can use:

您可以使用:

     dynamicArray.map(value => ({'key': value, 'val': 'whatever you want'}));

enter image description here

在此处输入图片说明