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

144
Views
Manipular objeto con JS

tengo este objeto:

 const data = { Jan: [{product: 'Shirt', num: '13'}, {product: 'Shoes', num: '15'}], Feb: [{product: 'Shirt', num: '22'}, {product: 'Shoes', num: '1'}], Mar: [{product: 'Shirt', num: '15'}, {product: 'Shoes', num: '25'}] }

Necesito crear otro objeto que se vea así:

 const data = { labels: ['Jan', 'Feb', 'Mar'], datasets: [ { label: 'Shirt', data: [13, 22, 15] }, { label: 'Shoes', data: [15, 1, 25] } ] }

El objeto de arriba es para un chartJs. La matriz de datos en la matriz de conjuntos de datos, correspondiente a cada valor del producto por mes.

Gracias de antemano

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

0

Puede crear el conjunto de datos usando Array.prototype.reduce y crear la nueva matriz de datos.

Tenga en cuenta que debe aplanar la matriz ya que Object.values(data) le brinda una matriz de matriz.

 const data = { Jan: [{product: 'Shirt', num: '13'}, {product: 'Shoes', num: '15'}], Feb: [{product: 'Shirt', num: '22'}, {product: 'Shoes', num: '1'}], Mar: [{product: 'Shirt', num: '15'}, {product: 'Shoes', num: '25'}] }; // Iterate through the data object's value and flatten this // For example the Object.values(data) will provide you- // [[{product: 'shirt', num: '13'}, {product: 'Shoes', num: '15'}], [{product: 'Shirt', num: '22'}, {product: 'Shoes', num: '1'}]] so on and so forth // Need to make this a linear array using flat(1) const dataset = Object.values(data).flat(1).reduce((acc, curr) => { // Check if the product exists on the accumulator or not. If not then create a new // object for the product. // For example, this will create - {'Shirt': {label: 'Shirt', data: [13]}} if (acc[curr.product] === undefined) { acc[curr.product] = { label: curr.product, data: [Number(curr.num)] } } else { // If the product already exists then push the num to the data array acc[curr.product].data.push(Number(curr.num)) } return acc; }, {}); const newData = { labels: Object.keys(data), // Set the keys as the labels dataset: Object.values(dataset) // dataset is an object, just extract the values as an array } console.log(newData);
 .as-console-wrapper{ min-height: 100vh!important; top: 0;}

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!