Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

244
Visualizações
Create object from array

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.

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

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.

over 4 years ago · Santiago Trujillo Relatório

0

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

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

console.log(obj)

Or maybe to solve your own original problem

const width = 1920
const height = 1080
const dynamicArray = ["2007", "2008", "2009", "2010"];
const obj = Object.fromEntries(
  dynamicArray.map((year, i) => [year, {
    x: (( i + 1) / 5) * width,
    y: height / 2
  }])
)

console.log(obj)

over 4 years ago · Santiago Trujillo Relatório

0

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

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}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda