Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

192
Views
¿Cómo crear una matriz JS que contenga un objeto JS como pares de valores clave de una cadena?

tengo un codigo javascript

 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));

esto dará el resultado como estos

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

pero necesito hacer uno como estos

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

Cómo puedo hacerlo ? Por favor ayúdenme y gracias de antemano.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Normalmente, solo harías

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

Su código solo se inserta en la matriz.

Primero debe crear un objeto y luego agregar el objeto a la matriz.

about 4 years ago · Juan Pablo Isaza Report

0

Tiene una matriz de matrices de claves y valores [[key, value, key, value]] . Si la matriz tuviera la forma de [[key, value], [key, value], ...] (entradas), podríamos usar Object.fromEntries() para convertirlo en un objeto.

Para transformar la matriz de entradas original, asigne la matriz, use Array.from() para convertir sub-matrices en tuplas de [key, value] y luego use Array.flat() para convertir la matriz 3d en una matriz 2d de entradas:

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!