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

73
Vistas
Ordenar un objeto por uno de sus campos para evitar repetir un bucle

Estoy tratando de ordenar un objeto para que no tenga que hacer el mismo ciclo n veces.

Dado el siguiente objeto

 movies = [ { title: "The Lord of the Rings: The Fellowship of the Ring" year: 2001 }, { title: "The Lord of the Rings: The Two Towers" year: 2002 }, { title: "The Lord of the Rings: The Return of the King" year: 2003 }, { title: "A Beautiful Mind" year: 2001 }, ]

Quiero que las películas estén ordenadas por año y que aparezcan en la pantalla:

 Year 2003 - The Lord of the Rings: The Return of the King Year 2002 - The Lord of the Rings: The Two Towers Year 2001 - A Beautiful Mind - The Lord of the Rings: The Fellowship of the Ring

Para hacer esto en vue , puedo hacer algo como definir un objeto years = [2003, 2002, 2001] y luego

 <div v-for="y in years"> {{ y }} <div v-for="m in movies"> <div v-if="m.year == y"> {{ m.title }} </div> </div> </div>

Sin embargo, de esta manera repito la v-for de las movies por la duración de la serie de years .

Así que pensé en organizar objetos de movies de la siguiente manera:

 moviesByYear = [ 2003: [ { title: "The Lord of the Rings: The Return of the King" year: 2003 } ], 2002: [ { title: "The Lord of the Rings: The Two Towers" year: 2002 } ], 2001: [ { title: "A Beautiful Mind" year: 2001 }, { title: "The Lord of the Rings: The Fellowship of the Ring" year: 2001 } ] ]

De esa manera podría usar

 <div v-for="(movies, year) in moviesByYear" :key="year"> <div>{{ year }}</div> <div v-for="m in movies"> {{ m.title }} </div> </div>

Desafortunadamente, no puedo construir la matriz moviesByYear y no estoy seguro de que sea el enfoque correcto porque hay inconvenientes para ordenar un objeto por claves. De hecho, necesitaría ordenar las películas por año ascendente y descendente.

¿Cómo podría solucionar este problema? ¿Existe un mejor enfoque que ejecutar v-for n veces?

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

0

Puede que no lo entienda bien, pero primero debe crear una matriz de objetos que contengan relaciones año => película. Puede crear el orden inverso (ascendente) simplemente invirtiendo la matriz. De esta manera, puede usar un v-for iterable simple, como

 <div v-for="year in movieList" > <div>{{ year.year }}</div> <div v-for="m in year.movies"> {{ m }} </div> </div> 

 let movies = [{ title: "The Lord of the Rings: The Fellowship of the Ring", year: 2009 }, { title: "The Lord of the Rings: The Two Towers", year: 2002 }, { title: "The Lord of the Rings: The Return of the King", year: 2003 }, { title: "A Beautiful Mind", year: 2009 }, ] let movieList = movies.reduce((b, a) => { let index = b.findIndex(f => f.year === a.year); if (index < 0) b.push({ year: a.year, movies: [a.title] }); else b[index].movies.push(a.title); return b; }, []).sort((a, b) => b.year - a.year); console.log(movieList) console.log('reversed: ', movieList.reverse())

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