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, }), )¿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);Lógica
items utilizando Array.map y Setitems contra el nombre y el tipooutput 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);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)