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

271
Views
¿Cómo hacer una matriz de objetos a partir de dos matrices no simétricas?

Estoy atascado ahora durante todo el día y no puedo avanzar más. Lo sé, que me falta una pequeña cosa, pero simplemente no puedo encontrarlo.

Tengo dos matrices:

 arrKeys = ["a", "b", "c"] arrValues = [ 1, 2, 3, 4, 5, 6, 7, 8, 9]

Me gustaría obtener una matriz de objetos, que se vea así:

 myObj = [ { "a": 1, "b": 2, "c": 3 }, { "a": 4, "b": 5, "c": 6 }, { "a": 7, "b": 8, "c": 9 } ]

Intenté hacer algo como:

 const myObj = arrKeys.reduce((newObj, key, index) => { if (arrValues[index] == undefined) arrValues[index] = null newObj[key] = aarValues[index] return newObj }, {}) cosnole.log(myObj)

Pero el problema es que arrKeys se repite solo una vez y no sé cómo "restablecer" el contador cada vez arrKeys alcanza la longitud máxima. También obtuve solo un objeto, no una matriz de objetos:

mi resultado

 myObj = { "a": 1, "b": 2, "c": 3 }

Cualquier idea es realmente apreciada.

about 4 years ago · Santiago Gelvez
3 answers
Answer question

0

Puede iterar sobre los valores, creando fragmentos arrKeys.length a la vez y luego creando un objeto a partir del fragmento asignando el índice del fragmento a la clave adecuada. Este enfoque tiene la ventaja de que si arrValues no es un múltiplo exacto de la longitud de arrKeys , seguirá funcionando:

 const f = (arrKeys, arrValues) => { const result = [] const kLen = arrKeys.length const vLen = arrValues.length for (i = 0; i < vLen; i += kLen) { chunk = arrValues.slice(i, i + kLen) result.push(Object.fromEntries(chunk.map((v, i) => [arrKeys[i], v]))) } return result; } console.log(f(["a", "b", "c"], [1, 2, 3, 4, 5, 6, 7, 8, 9])) console.log(f(["a", "b", "c"], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])) console.log(f(["a", "b", "c", "d"], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]))

about 4 years ago · Santiago Gelvez Report

0

Puede usar el operador de módulo para verificar cada elemento keys.length nth y luego agregar un nuevo objeto cortando la matriz de valores donde el inicio es el índice actual y el final el índice actual + keys.length

 const f = (keys, values) => values.reduce((r, e, i) => { if (i % keys.length === 0) { const index = i / keys.length r[index] = values.slice(i, i + keys.length).reduce((r, e, i) => { r[keys[i]] = e return r }, {}) } return r }, []) console.log(f(["a", "b", "c"], [1, 2, 3, 4, 5, 6, 7, 8, 9])) console.log(f(["a", "b", "c", 'g'], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])) console.log(f(["a", "b"], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]))

about 4 years ago · Santiago Gelvez Report

0

Una forma sería recorrer los arrValues usando un for...loop convencional.

Podemos usar el operador de módulo % para determinar dónde estamos en la serie de tres.

Consulte lo siguiente para ver una demostración:

 var arrKeys = ["a", "b", "c"]; var arrValues = [ 1, 2, 3, 4, 5, 6, 7, 8, 9]; var myObj = []; var newObj = null; for(var i=0; i<arrValues.length; i++) { if(i % 3 === 0) // First run of three newObj = {}; newObj[ arrKeys[i % 3] ] = arrValues[i]; if(i % 3 === 2) // We're at the end of the run of three myObj.push(newObj); } console.log(myObj);

about 4 years ago · Santiago Gelvez 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!