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

113
Visualizações
How to make an array of object from 2 arrays

Let's say I have any array like:

a = ["name", "age"] and then an array of arrays like b = [["Alex", 20], ["Ari", 25], ..] I want to make an array of object that get its keys from a and values from b

[{
  name: "Alex",
  age: 20
}, 
{
  name: "Ari",
  age: 25
}]

I tried the following:

for (const arr of b) {
  Object.assign({}, arr)
}

which makes an object but doesn't use keys of array a.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

const a = ["name", "age"]
const b = [["Alex", 20], ["Ari", 25]]

const output = b.map(item => {
 return a.reduce((aggr, curr, i) => (aggr[curr] = item[i], aggr), {});
});

console.log(output);

However the code assumes the length of a always matches length of each item in b. Make sure to guard it properly.

In case you were pondering about the statement in parentheses (aggr[curr] = item[i], aggr), this is JavaScript's comma operator which executes all comma-delimited statements and returns the value of the last one - in this case aggr (which we need to return for next iteration of .reduce to aggregate the object).

about 4 years ago · Juan Pablo Isaza Relatório

0

If you want something in Python you can also try this.

my_list = []
a = ['name','age']
b = [['alex', 20], ['ari', 25], ['pete', 45], ['alf', 67]]

for person in b:
    temp = {}
    for i in range(len(a)):
        temp[a[i]] = person[i]
    my_list.append(temp)
about 4 years ago · Juan Pablo Isaza 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