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

182
Visualizações
Javascript: quick object initialization by list

Suppose I have the object a

const a = {
  string1: 'prop1',
  val1: 'value1',
  string2: 'prop2',
  val2: 'value2'
}

then I can easily instantiate a new constant object b

const b = { [a['string1']]: a['val1'], [a['string2']]: a['val2'] };

which will result in

b = { prop1: 'value1', prop2: 'value2' }

But what if I have instead a list lst

const lst = [['prop1','value1'], ['prop2','value2']]

and I want to instantiate b from lst in a neat way? The furthest I got was

const b = {};
for(const tpl of lst){
  b[tpl[0]] = tpl[1];
}

But me, being a big fan of oneliners, do not really like this code. So how can I quickly initialise b from a list of properties?

EDIT It seems my question was not posed abstractly enoughed. Let me reclarify it. Suppose I have the list l = ['prop1', 'prop2'];

and the function fx(str) { return str.substring(1); } How could I now quickly initialize the object b such that

b = {
  prop1: 'rop1',
  prop2: 'rop2'
}

I cannot do b= {[l[0]]=fx(l[0]), [l[1]]=fx(l[1])} since the list l is dynamicly generated and will contain an unknown amount of variables. So somehow it would be nice to loop e.g. this non-existent syntax

b = { [[for str in l]] : fx(str) }
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You have entries there, so you can just:

Object.fromEntries(lst)
about 4 years ago · Juan Pablo Isaza Relatório

0

As Uroš mentioned Object.fromEntries(lst) is the best method for this. As an alternative you can use reduce.

const lst = [['prop1','value1'], ['prop2','value2']]

const b =  lst.reduce(function(prev,curr){prev[curr[0]]=curr[1];return prev;},{})
console.log(b);

about 4 years ago · Juan Pablo Isaza Relatório

0

You can use the .values() method

const b = {};
const lst = [
  ['prop1', 'value1'],
  ['prop2', 'value2'],
];

for (const [key, value] of lst.values()) b[key] = value;

console.log(b);

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