从数组创建对象 [英] Create object from array
问题描述
我想从数组中的列表创建一个对象.我有一个动态数组,应该如下所示:
var dynamicArray = [2007"、2008"、2009"、2010"];
我想用一些 JavaScript ES6 创建一个这样的对象:
const obj = {2007 年:{x:宽度/5,y:高度/2},2008 年:{x: (2/5) * 宽度,y:高度/2},2009 年:{x: (3/5) * 宽度,y:高度/2},2010 年:{x: (4/5) * 宽度,y:高度/2}}
不要担心内部对象.我只想创建一个这样的结构:
obj = {2007 年:...,2008 年:...,...}
请帮忙,谢谢.
简单
const obj = {};for ( yourArray 的常量键) {obj[key] = 随便什么;}
或者如果您更喜欢功能性"风格:
const obj = yourArray.reduce((o, key) => Object.assign(o, {[key]:whatever}), {});
使用现代对象扩展运算符:
const obj = yourArray.reduce((o, key) => ({ ...o, [key]:whatever}), {})
示例:
<预><代码>[{ id: 10, 颜色: "红色" },{ id: 20, 颜色: "blue" },{ ID:30,颜色:绿色"}].reduce((acc, cur) => ({ ...acc, [cur.color]: cur.id }), {})输出:
{红色:10,蓝色:20,绿色:30}
这是它的工作原理:
reduce
被初始化为一个空对象(空 {}
末尾),因此第一次迭代变量是 acc = {}
<代码>cur = { id: 10, color: "red" }.函数返回一个对象——这就是为什么函数体用括号括起来的原因 =>;({ ... })
.展开运算符在第一次迭代时不做任何事情,因此将 red: 10
设置为第一项.
第二次迭代的变量是acc = { red: 10 }
cur = { id: 20, color: "blue" }
.这里展开运算符 expands acc
并且函数返回 { red: 10, blue: 20 }
.
第三次迭代acc = { red: 10, blue: 20 }
cur = { id: 30, color: "green" }
,所以当acc
散布在对象内部,我们的函数返回最终值.
I want to create an object from a list inside an array. I have an array which is dynamic and supposed to look like this:
var dynamicArray = ["2007", "2008", "2009", "2010"];
And I want to make an object like this with some 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 the inner objects. I just want to create a structure like this:
obj = {
2007: ...,
2008: ...,
...
}
Please help, thanks.
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:
reduce
is 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: 10
is set as first item.
On the second iteration variables are acc = { red: 10 }
cur = { id: 20, color: "blue" }
. Here the spread operator expands acc
and the function returns { red: 10, blue: 20 }
.
Third iteration acc = { red: 10, blue: 20 }
cur = { id: 30, color: "green" }
, so when acc
is spread inside the object, our function returns the final value.
这篇关于从数组创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!