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

193
Vistas
How to create a JS Array containing an JS Object as Key value pairs from string?

I Have a javascript code

var jsString1 = [];
var jsString = [];
var val1, val2;
val1 = "test1";
val2 = "test2";
jsString1.push("key1");
jsString1.push(val1);
jsString1.push("key2");
jsString1.push(val2);
jsString.push(jsString1);
alert(JSON.stringify(jsString));

this will give the result as these

// current output
 [["key1","test1","key2","test2"]]

but I need to make one like these

// needed output
 [{"key1":"test1","key2":"test2"}]

How can I do it ? Please help me and thanks in advance.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Normally, you would only do

jsString1.push({
    "key1": val1 "key2": val2
})

Your code only pushes into the array.

You need to create an object first, and then add the object into the array.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You have an array of arrays of keys and values [[key, value, key, value]]. If the array was in the form of [[key, value], [key, value], ...] (entries) we could use Object.fromEntries() to convert it to an object.

To transform the original an array of entries, map the array, use Array.from() to convert sub-arrays to tuples of [key, value], and then use Array.flat() to convert the 3d array to a 2d array of entries:

const toEntries = arr =>
  arr.map(subArr => 
    Array.from({ length: subArr.length / 2 }, (_, i) => 
      subArr.slice(i * 2, i * 2 + 2)
    )
  ).flat(1)

const arr = [["key1","test1","key2","test2"]];

const obj = Object.fromEntries(toEntries(arr))

console.log(JSON.stringify(obj));

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