Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

72
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda