Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

335
Vistas
¿Cómo puedo contar valores y obtener otra estructura de matriz?

Tengo una matriz de objetos y quiero convertirlos para consumir los datos en un gráfico. Alguien recomienda usar lodash, pero no quiero usar ninguna biblioteca. Así que aquí está el ejemplo de la matriz:

 const items = [ { priceChangeType: 'CL', hierarchy: { department: { description: 'TEXTILES', }, }, }, { priceChangeType: 'PM', hierarchy: { department: { description: 'CLOTHES', }, }, }, { priceChangeType: 'CL', hierarchy: { department: { description: 'TEXTILES', }, }, }, { priceChangeType: 'CL', hierarchy: { department: { description: 'CLOTHES', }, }, }, { priceChangeType: 'PM', hierarchy: { department: { description: 'BATH', }, }, }, { priceChangeType: 'PM', hierarchy: { department: { description: 'TOOLS', }, }, }, { priceChangeType: 'CL', hierarchy: { department: { description: 'TOOLS', }, }, }, { priceChangeType: 'CL', hierarchy: { department: { description: 'TOOLS', }, }, }, ]

Y quiero una salida como esta, y este es el formato necesario para el gráfico.

 const data = [ {name: 'TOOLS', PM: 1, CL: 2}, {name: 'CLOTHES', PM: 1, CL: 1}, {name: 'TEXTILES', PM: 0, CL: 2}, {name: 'BATH', PM: 1, CL: 0}, ]

Esto es lo más lejos que he llegado, pero solo cuenta el total.

 const totalPriceChangesType = Object.entries(items.reduce((r, v, i, a, k = v.priceChangeType) => ((r[k] || (r[k] = [])).push(v), r), {})).map( ([key, value]) => ({ [key] : value.length, }), )
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

¿Quizás este ejemplo pueda ayudarte?

 const items = [{ priceChangeType: "CL", hierarchy: { department: { description: "TEXTILES" } } }, { priceChangeType: "PM", hierarchy: { department: { description: "CLOTHES" } } }, { priceChangeType: "CL", hierarchy: { department: { description: "TEXTILES" } } }, { priceChangeType: "CL", hierarchy: { department: { description: "CLOTHES" } } }, { priceChangeType: "PM", hierarchy: { department: { description: "BATH" } } }, { priceChangeType: "PM", hierarchy: { department: { description: "TOOLS" } } }, { priceChangeType: "CL", hierarchy: { department: { description: "TOOLS" } } }, { priceChangeType: "CL", hierarchy: { department: { description: "TOOLS" } } } ]; // collect all possible PM, CL, etc. (example: {PM:0, CL:0}) const priceChangeTypes = items.reduce((acc, item) => (acc[item.priceChangeType] = 0, acc), {}); const total = Object.values(items.reduce((acc, item) => { const descriprion = item.hierarchy.department.description; const priceChangeType = item.priceChangeType; // create a new base object {name: "{description}", PM:0, CL:0, ...} if (!acc[descriprion]) acc[descriprion] = { name: descriprion, ...priceChangeTypes }; acc[descriprion][priceChangeType]++; return acc; }, {})); console.log(total);

about 4 years ago · Juan Pablo Isaza Denunciar

0

Lógica

  • Genere tipos únicos a partir de la matriz de items utilizando Array.map y Set
  • Reduzca la matriz de items contra el nombre y el tipo
  • Agregue el tipo que falta a los nodos individuales en la matriz de output

 const items = [{priceChangeType: 'CL',hierarchy: {department: {description: 'TEXTILES'}}},{priceChangeType: 'PM',hierarchy: {department: {description: 'CLOTHES'}}},{priceChangeType: 'CL',hierarchy: {department: {description: 'TEXTILES'}}},{priceChangeType: 'CL',hierarchy: {department: {description: 'CLOTHES'}}},{priceChangeType: 'PM',hierarchy: {department: {description: 'BATH'}}},{priceChangeType: 'PM',hierarchy: {department: {description: 'TOOLS'}}},{priceChangeType: 'CL',hierarchy: {department: {description: 'TOOLS'}}},{priceChangeType: 'CL',hierarchy: {department: {description: 'TOOLS'}}}]; // Generate unique types const types = Array.from(new Set(items.map(item => item.priceChangeType))); // Reduce the items array against the name and type const output = items.reduce((acc, curr, index, array, name = curr.hierarchy.department.description, type = curr.priceChangeType) => { acc[name] = acc[name] || {}; acc[name][type] = ++acc[name][type] || 1; return acc; }, {}); // Add the missing type to each object in output Object.entries(output).forEach(([key, value]) => types.forEach(type => output[key][type] = output[key][type] || 0)) console.log(output);

about 4 years ago · Juan Pablo Isaza Denunciar

0

Puede crear un objeto ( priceChangeTypes ) de todos los priceChangeType inicializados en 0 asignando la matriz a [priceChangeType, 0] pares y usando Object.fromEntries() .

Luego reduzca la matriz original a un Mapa. Para cada nueva hierarchy.department.description cree una entrada en el Mapa distribuyendo priceChangeTypes a un nuevo objeto e incremente el priceChangeType relevante.

Vuelva a convertir a una matriz usando Array.from() .

 const items = [{priceChangeType: 'CL',hierarchy: {department: {description: 'TEXTILES'}}},{priceChangeType: 'PM',hierarchy: {department: {description: 'CLOTHES'}}},{priceChangeType: 'CL',hierarchy: {department: {description: 'TEXTILES'}}},{priceChangeType: 'CL',hierarchy: {department: {description: 'CLOTHES'}}},{priceChangeType: 'PM',hierarchy: {department: {description: 'BATH'}}},{priceChangeType: 'PM',hierarchy: {department: {description: 'TOOLS'}}},{priceChangeType: 'CL',hierarchy: {department: {description: 'TOOLS'}}},{priceChangeType: 'CL',hierarchy: {department: {description: 'TOOLS'}}}] // Create an initialized counts object = { CL: 0, PM: 0 } const priceChangeTypes = Object.fromEntries(items.map(o => [o.priceChangeType, 0])) const result = Array.from( items.reduce((acc, o) => { const key = o.hierarchy.department.description // initialize the object for the current key if needed if(!acc.has(key)) acc.set(key, { ...priceChangeTypes }) // increment the relevant priceChangeType acc.get(key)[o.priceChangeType] += 1 return acc }, new Map()), ([names, values]) => ({ name, ...values }) // convert to an array ) console.log(result)

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda