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

163
Visualizações
Cómo agrupar por valor de clave dinámica de un objeto de matrices (mes y año)

Esta pregunta es una extensión de esta pregunta aquí. Subrayar el grupo js por cada mes en cada año en un solo nivel

El código que estoy usando está aquí.

 const months = [ 'January','February','March','April','May','June','July','August','September','October','November','December' ] const result = flashMessage.reduce((res:any, item:any) => { const date = new Date(item.created_at) const year = date.getFullYear(); const month = months[date.getMonth()]; const existingYear=res[`${month} ${year}`] ||[]; const updated = [...(existingYear[month] || []), item] const returnItem = { title:item.title, user_message:item.user_message, created_at:item.created_at }; res[`${month} ${year}`] = [...existingYear,returnItem] return res }, {});

El código anterior está produciendo el resultado esperado, pero está fuera de servicio. Aquí está el resultado del código anterior. [![ingrese la descripción de la imagen aquí][1]][1]

Quiero que el resultado esté en orden. El orden que quería se muestra a continuación.

marzo 2022

febrero 2022

enero 2022

marzo 2021

febrero 2021

enero 2021

Entonces, ¿cómo puedo hacer eso? [1]: https://i.stack.imgur.com/BS9ZS.png

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Esta puede ser una posible solución para lograr el objetivo deseado.

 // 'sortedKeys' will hold only the keys of the 'res' object // but these will be in a sorted-order (based on prop 'created_at') const sortedKeys = [ ...Object.keys(result) ].sort( (a, b) => ( result[a][0]['created_at'] > result[b][0]['created_at'] ? -1 : 1 ) ); // to render in the sorted order, use 'sortedKeys' like this sortedKeys.forEach(k => { console.log('key: ', k, ' value: ', result[k]) });

Acercarse

  • Primero obtenga las claves del objeto de result
  • A continuación, extiéndalos y luego aplique .sort()
  • La matriz ordenada se almacena en la matriz sortedKeys
  • El .sort emplea el objeto de result created_at prop correspondiente al valor de cada key .
  • Para validar la ordenación, itere sobre la matriz sortedKeys usando .forEach y muestre la clave k y el valor correspondiente del objeto de result .

Fragmento de código

A continuación, se proporciona un ejemplo de trabajo de las claves ordenadas generadas

 const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; const flashMessage = [ { created_at: '2021-03-11T06:40:46.790Z', title: 'Announcement 02', user_message: 'see more test', }, { created_at: '2021-01-11T06:40:46.790Z', title: 'Announcement 25', user_message: 'see more test', }, { created_at: '2021-02-11T06:40:46.790Z', title: 'This is a push notification to all', user_message: 'A push notification to all' }, { created_at: '2022-01-11T06:40:46.790Z', title: 'title for jan 2021', user_message: 'message for jan 2021' }, { created_at: '2022-03-11T06:40:46.790Z', title: 'title for mar 2021', user_message: 'message for mar 2021' }, { created_at: '2022-02-11T06:40:46.790Z', title: 'title for feb 2021', user_message: 'message for feb 2021' } ]; const result = flashMessage.reduce((res, item) => { const date = new Date(item.created_at) const year = date.getFullYear(); const month = months[date.getMonth()]; const existingYear = res[`${month} ${year}`] || []; const updated = [...(existingYear[month] || []), item] const returnItem = { title: item.title, user_message: item.user_message, created_at: item.created_at }; res[`${month} ${year}`] = [...existingYear, returnItem] return res }, {}); const sortedKeys = [ ...Object.keys(result) ].sort( (a, b) => ( result[a][0]['created_at'] > result[b][0]['created_at'] ? -1 : 1 ) ); console.log('keys of result object sorted: ', sortedKeys); sortedKeys.forEach(k => { console.log('key: ', k, ' value: ', result[k]) });

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