本文介绍了从数组创建对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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];

和一些javascript es6我想创建一个这样的对象:

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

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

不要担心内部对象,只是想要一个make结构像这样:

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

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

请帮助,谢谢。

推荐答案

简单

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

示例:

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

输出:

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

以下是它的工作原理:

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

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.

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

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

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

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.

这篇关于从数组创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 00:07