Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

75
Views
Llenar una matriz de objetos con 0 si el objeto no existe

Estoy creando un gráfico para datos mensuales que tendría el eje x como wk1 - wk4 y el eje y sería la cantidad de bienes, etc. Pude construir una solución, pero el problema radica cuando no hay datos para una semana en particular. Este es mi código a continuación.

 const byAmount = obj => { const res = []; const keys = Object.keys(obj); keys.forEach(key => { res.push({ week: `wk${key}`, amount: obj[key] }); }); return res.sort((a, b) => a.amount - b.amount).slice(0, 5);; }; const getWeeklyFromMonth = (arr, month) => { const week = arr.map(a => ({ ...a, week: Math.floor((moment(a.dateScanned.$date).date() - 1) / 7) + 1 })); let dataForMonth = []; let total; week.map(data => { if (moment(data.dateScanned.$date).format("MMM") === month) { dataForMonth.push(data); const totalPerWeek = dataForMonth.reduce((acc, cur) => { acc[cur.week] = acc[cur.week] + cur.amount || cur.amount; return acc; }, {}); total = totalPerWeek; } }); return byAmount(total); }

Cuando ejecuto esto me sale lo siguiente:

 [ { week: 'wk1', amount: 14 }, { week: 'wk2', amount: 27 }, { week: 'wk4', amount: 43 } ]

Esto está bien, pero quiero llenar la matriz con 0 si no hay datos, por ejemplo, para la semana 3. Me gustaría que fuera así

 [ { week: 'wk1', amount: 14 }, { week: 'wk2', amount: 27 }, { week: 'wk3', amount: 0 }, { week: 'wk4', amount: 43 } ]

Estaba pensando en tener una matriz como [1, 2, 3, 4] y si la matriz incluye el número de la semana, sáquelo de la matriz y luego el elemento restante debería usarse para completarlo, pero me encuentro rascándome la cabeza. cabeza. ¿Alguien sabe una manera decente de hacer esto?

Gracias de antemano.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Puedes probar esto:

 const byAmount = obj => { const res = []; const keys = Object.keys(obj); const [min, max] = [Math.min(...keys), Math.max(...keys)]; for(let key = min; key <= max; key++) { res.push({ week: `wk${key}`, amount: obj[key] || 0 }); } return res.sort((a, b) => a.amount - b.amount).slice(0, 5);; };
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!