2

Hola buenos días espero me puedan ayudar, actualmente tengo un problema con una estructura json la cual viene de la siguiente forma,dicha estructura contiene la fecha de creación, esta tiene el siguiente formato: YYYYMMDD

[
    {
        "society": "1000",
        "centro": "2005",
        "nameStore": "TIENDA",
        "dateOfCreation": "2021-01-11",
        "yearCreation": "2021"
    },
    {
        "society": "1000",
        "centro": "3008",
        "nameStore": "TIENDA",
        "dateOfCreation": "2021-01-08",
        "yearCreation": "2021"
    },
    {
        "society": "1000",
        "centro": "3006",
        "nameStore": "TIENDA",
        "dateOfCreation": "2021-01-09",
        "yearCreation": "2021"
    },
    {
        "society": "1000",
        "centro": "3001",
        "nameStore": "TIENDA",
        "dateOfCreation": "2021-01-09",
        "yearCreation": "2021"
    },
]

y deseo obtener la siguiente estructura mas sin embargo hasta el momento no he podido lograrlo con exito:

[
    {
        "year": "2021",
        "months": [
            {
                "month": "01",
                "data": [
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    },
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    }
                ]
            },
            {
                "month": "02",
                "data": [
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    },
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    }
                ]
            },
            {
                "month": "03",
                "data": [
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    },
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    }
                ]
            },
            {
                "month": "04",
                "data": [
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    },
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    }
                ]
            },
            {
                "month": "05",
                "data": [
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    },
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    }
                ]
            },
            {
                "month": "06",
                "data": [
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    },
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    }
                ]
            },
            {
                "month": "07",
                "data": [
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    },
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    }
                ]
            },
            {
                "month": "08",
                "data": [
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    },
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    }
                ]
            },
            {
                "month": "09",
                "data": [
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    },
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    }
                ]
            },
            {
                "month": "10",
                "data": [
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    },
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    }
                ]
            },
            {
                "month": "11",
                "data": [
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    },
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    }
                ]
            },
            {
                "month": "12",
                "data": [
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    },
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    }
                ]
            }
        ]
    },
    {
        "year": "2022",
        "months": [
            {
                "month": "01",
                "data": [
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    },
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    }
                ]
            },
            {
                "month": "02",
                "data": [
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    },
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    }
                ]
            },
            {
                "month": "03",
                "data": [
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    },
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    }
                ]
            },
            {
                "month": "04",
                "data": [
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    },
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    }
                ]
            },
            {
                "month": "05",
                "data": [
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    },
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    }
                ]
            },
            {
                "month": "06",
                "data": [
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    },
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    }
                ]
            },
            {
                "month": "07",
                "data": [
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    },
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    }
                ]
            },
            {
                "month": "08",
                "data": [
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    },
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    }
                ]
            },
            {
                "month": "09",
                "data": [
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    },
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    }
                ]
            },
            {
                "month": "10",
                "data": [
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    },
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    }
                ]
            },
            {
                "month": "11",
                "data": [
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    },
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    }
                ]
            },
            {
                "month": "12",
                "data": [
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    },
                    {
                        "society": "1000",
                        "centro": "3006",
                        "nameStore": "TIENDA",
                        "dateOfCreation": "2021-01-09",
                        "yearCreation": "2021"
                    }
                ]
            }
        ]
    },
]

Hasta el momento lo mas cerca que he estado de resolver el problema ha sido mediante esta función:

groupByMonthWeek(data: any) {
    var year;

    return data.reduce(function (acc: any, obj: any) {

      var b = obj.dateOfCreation.split(/\D/);

      // Add year if not already present
      if (!acc[b[0]]) acc[b[0]] = {};
      year = acc[b[0]];

      // Add month if not already present
      if (!year[b[1]]) year[b[1]] = [];

      year[b[1]].push(obj);
      
      return acc;
    }, Object.create(null));
  }

Espero que alguién haya pasado por lo mismo y pueda compartirme una solución a este problema.

Gracias de antemano.

3 respuestas 3

0

con un simple reduce podrías obtener el resultado que quieres:

const data = [
    {
        "society": "1000",
        "centro": "2005",
        "nameStore": "TIENDA",
        "dateOfCreation": "2021-01-11",
        "yearCreation": "2021"
    },
    {
        "society": "1000",
        "centro": "3008",
        "nameStore": "TIENDA",
        "dateOfCreation": "2021-01-08",
        "yearCreation": "2021"
    },
    {
        "society": "1000",
        "centro": "3006",
        "nameStore": "TIENDA",
        "dateOfCreation": "2021-01-09",
        "yearCreation": "2021"
    },
    {
        "society": "1000",
        "centro": "3001",
        "nameStore": "TIENDA",
        "dateOfCreation": "2021-02-09",
        "yearCreation": "2021"
    },
];

const result = data.reduce((accum, value) => {
   const [year,month] = value['dateOfCreation'].split('-');
   
   //Buscas el año, si no está en el resultado lo creas
   let existingYear = accum.find(x => x.year===year);
   if(!existingYear){
      accum.push({ year, months: []});
      existingYear = accum.find(x => x.year===year);
   };

   //ahora, dentro de ese año buscas el mes... si no está, lo creas
   const existingMonth = existingYear.months.find(x => x.month===month);
   if(existingMonth){
      existingMonth.data.push(value);
   } else {   
      existingYear.months.push({ month, data: [value]}); //Ya con el dato insertado
   }
   
   return accum;
}, [])

console.log(result);

Cualquier duda me puedes preguntar en los comentarios

0

Prueba con este código, fue lo primero que se me ocurrió.

    function groupByMonthWeek(data) {
        return data.reduce((acc, ele) => {
            const index = acc.findIndex((ele2) => ele2.year == ele.yearCreation);
            const nuevo = [...acc];
            const mesNuevo = ele.dateOfCreation.split(/\D/)[1];
            if (index != -1) {
                const meses = nuevo[index].months;
                const iMes = meses.findIndex((mes) => mes.month == mesNuevo);
                if (iMes != -1) {
                    meses[iMes].data.push(ele);
                } else {
                    meses.push({ month: mesNuevo, data: [{...ele}] });
                }
                nuevo[index].months = [...meses];
            } else {
                nuevo.push({
                    year: ele.yearCreation,
                    months: [{ month: mesNuevo, data: [{ ...ele }] }],
                });
              }
            return nuevo;
      }, []);
    }
2
  • Igual no esta demás por favor consultes Cómo responder y agregues una explicación de como este script ayuda a solventar la duda expuesta
    – user128299
    Commented el 9 mar. 2022 a las 18:16
  • Tal y como está redactada, tu respuesta no es clara. Por favor, pulsa en editar para añadir detalles adicionales que ayuden a los demás a entender cómo esto responde a la pregunta formulada. Puedes encontrar más información sobre cómo escribir buenas respuestas en el centro de ayuda.
    – Comunidad Bot
    Commented el 9 mar. 2022 a las 18:46
0

Puedes probar lo siguiente (he modificado tu JSON para que se generen agrupaciones) :

  • Utilizar reduce para agrupar los elementos por año y mes:
grouped_data = data.reduce(function(r, x) {
    month = x['dateOfCreation'].split('-')[1];
  
  r[x['yearCreation']] = r[x['yearCreation']] || {};
  (r[x['yearCreation']][month] = r[x['yearCreation']][month] || []).push(x)
  
  return r;
}, {})

Esto nos devuelve un objeto con esta estructura:

{
  "2021": {
    "02": [
      {
        "society": "1000",
        "centro": "2005",
        "nameStore": "TIENDA",
        "dateOfCreation": "2021-02-11",
        "yearCreation": "2021"
      }
    ],
    "01": [
      {
        "society": "1000",
        "centro": "3008",
        "nameStore": "TIENDA",
        "dateOfCreation": "2021-01-08",
        "yearCreation": "2021"
      },
      {
        "society": "1000",
        "centro": "3006",
        "nameStore": "TIENDA",
        "dateOfCreation": "2021-01-09",
        "yearCreation": "2021"
      }
    ]
  },
  "2022": {
    "01": [
      {
        "society": "1000",
        "centro": "3001",
        "nameStore": "TIENDA",
        "dateOfCreation": "2021-01-09",
        "yearCreation": "2022"
      }
    ]
  }
}

Con esa estructura anidada puedes convertirla al formato que necesitas iterando por cada key del objeto en los dos niveles con algo similar a:

result = Object.keys(grouped_data).map(function(k){
    return {
    year: k,
    months: Object.keys(grouped_data[k]).map(function(l){
        return {
        month: l,
        data: grouped_data[k][l]
      }
    })
  }
});

// O en formato arrow function
result = Object.keys(grouped_data).map(k => (
    {year: k, months: Object.keys(grouped_data[k]).map(l => ({month: l, data: grouped_data[k][l]}))}
));

data = [
    {
        "society": "1000",
        "centro": "2005",
        "nameStore": "TIENDA",
        "dateOfCreation": "2021-02-11",
        "yearCreation": "2021"
    },
    {
        "society": "1000",
        "centro": "3008",
        "nameStore": "TIENDA",
        "dateOfCreation": "2021-01-08",
        "yearCreation": "2021"
    },
    {
        "society": "1000",
        "centro": "3006",
        "nameStore": "TIENDA",
        "dateOfCreation": "2021-01-09",
        "yearCreation": "2021"
    },
    {
        "society": "1000",
        "centro": "3001",
        "nameStore": "TIENDA",
        "dateOfCreation": "2021-01-09",
        "yearCreation": "2022"
    },
];

grouped_data = data.reduce(function(r, x) {
    month = x['dateOfCreation'].split('-')[1];
  
  r[x['yearCreation']] = r[x['yearCreation']] || {};
  (r[x['yearCreation']][month] = r[x['yearCreation']][month] || []).push(x)
  
  return r;
}, {})

result = Object.keys(grouped_data).map(k => (
    {year: k, months: Object.keys(grouped_data[k]).map(l => ({month: l, data: grouped_data[k][l]}))}
));


console.log(result)

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.