Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

183
Vistas
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 Respuestas
Responde la pregunta

0

You have entries there, so you can just:

Object.fromEntries(lst)
about 4 years ago · Juan Pablo Isaza Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda