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

128
Vistas
push element of array to object as value

I want to change an array to object like this :

array = ["blue" , "txt2" , "red" ,"txt4" , "txt5" , "txt6" ,"txt7" , "txt8" , "txt9" ]
   
pages = {"page1" :["blue","txt2", "red"] , "page2" : ["txt4", "txt5", "txt6"], "page3" : ["txt7" ,"txt8", "txt9"]   

Every key in pages object should have an array value with 3 elements of array (the last key can have less) , so for example if an array have 110 elements we will have 37 pages (page1 , page 2 , ... , page37) and page37 will have 1 elements.

So I want put every 3 elements in array as value of a key in the pages object

But I don't know how to do it.. Thank you for your help

about 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

You can do it by iterating over array and extract 3 items from array on every iteration by using splice method, like this:

let array = ["blue" , "txt2" , "red" ,"txt4" , "txt5" , "txt6" ,"txt7" , "txt8" , "txt9", "text10" ]
let pages= {}, i= 1;
while(array.length > 0){
    pages[`page${i++}`] = array.splice(0,3)
}

console.log(pages)

with this manner, you loose the original values in the array, if you want to keep items in the array untuched, you can make copy of your original data like let copiedArray = [...array] and then call splice method on the copiedArray and also check the length of copiedArray in the while.

about 4 years ago · Santiago Trujillo Denunciar

0

Get every third index and add all the elements from that point to that point plus three (if that index is near the end it won't error; it will just add the remaining elements):

const initial = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];

let paginated = {};
let counter = 0

while (counter < initial.length) {
 paginated['page' + parseInt(counter / 3 + 1)] = initial.slice(counter, counter + 3);
 counter += 3;
}
 
console.log(paginated);

about 4 years ago · Santiago Trujillo Denunciar

0

For a more configurable solution you might look to a chunk utility function for the initial division of the input array, and then map that as desired to your result object (here using Object.fromEntries and mapping over the resulting chunked array to assign 'page' keys based on index).

function chunk(arr, chunkSize) {
  const result = [];
  for (let i = 0; i < arr.length; i += chunkSize) {
    result.push(arr.slice(i, i + chunkSize));
  }

  return result;
}

const array = ['blue', 'txt2', 'red', 'txt4', 'txt5', 'txt6', 'txt7', 'txt8', 'txt9'];

const result = Object.fromEntries(
    chunk(array, 3).map((chunk, index) => [`page${index + 1}`, chunk])
);

console.log(result);

see: Split array into chunks for discussion.

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