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

173
Vistas
¿Cómo hago para que la primera mitad de los valores de una matriz se conviertan en claves y la otra mitad en valores de esas claves?

tengo lo siguiente:

const array = [{value: 'banana'}, {value: 'apple'}, {value: 'yellow'}, {value: 'red'}]

Necesito lo siguiente:

const result = [{banana: 'yellow'}, {apple: 'red'}];

¿Hay alguna forma de crear resultados a partir de la matriz, utilizando bucles o funciones de orden superior en JavaScript?

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

0

Puedes usar Array.prototype.flatMap :

 const flatMapToEntry = (key, index, array) => { const length = array.length / 2; if (index >= length) { return []; } const value = array[index + length]; return [{ [key]: value }]; }; const result = array.map(o => o.value).flatMap(flapMapToEntry);
about 4 years ago · Juan Pablo Isaza Denunciar

0

Aquí hay una respuesta que usa la misma lógica provista en el comentario. Esto tiene descripciones relevantes para ayudar a entender mejor.

 const getMyObject = arr => { // first compuate the half-length "lenBy2" of given array const lenBy2 = Math.floor(arr.length / 2); // return the "result" as an object return Object .fromEntries( // generate object from key-value pairs below arr.map( // iterate "arr" to obtain key-value pairs ({ value }, idx) => ( // get the index "idx" and de-structure to access "value" idx < lenBy2 // if index less than half-length "lenBy2" ? [ // return key-value pair as a 2-element array value, // [ "banana", "yellow" ], for example arr[idx + lenBy2]?.value ] : [] // if index >= half-length, return empty array ) ).filter( // filter key-value pairs to retain only non-empty ones x => x.length == 2 ) ); }; // below are steps only to generate results for various test cases // the original array from the question const array1 = [{value: 'banana'}, {value: 'apple'}, {value: 'yellow'}, {value: 'red'}]; // test-case 2 - an array with 3 pairs const array2 = [ {value: 'banana'}, {value: 'apple'}, {value: 'tomato'}, {value: 'yellow'}, {value: 'green'}, {value: 'red'} ]; // mismatched array where the fruit "orange" has no matching color const array3 = [ {value: 'banana'}, {value: 'apple'}, {value: 'orange'}, {value: 'yellow'}, {value: 'red'} ]; // mismatched array where the color "orange" has no matching fruit const array4 = [ {value: 'banana'}, {value: 'apple'}, {value: 'yellow'}, {value: 'red'}, {value: 'orange'} ]; // iterate over the various test case arrays & // console.log the result [array1, array2, array3, array4].forEach((arr, idx) => console.log( `\n***---> test case ${idx + 1} <---***\n`, 'given array: 👉 ', JSON.stringify(arr), '\n\nresult object: 👇 \n', getMyObject(arr), '\n ***---> end of result <---*** \n\n' ) );
 .as-console-wrapper { max-height: 100% !important; top: 0 }

Siéntase libre de publicar preguntas en los comentarios, en caso de que no esté claro cómo funciona lo anterior.

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