Tengo una estructura de datos como
const dd = [{ keyone: "test", two: "you", three: 'op', }, { keyone: "youuuu", two: "ttt", three: 'op', }, { keyone: "operation", two: "test", three: 'op', }];Y quiero poder sacar keyone y two en un objeto como el siguiente
const obj = { keyone: ['test', 'youuuu', 'operation'], two: ['you', 'ttt', 'test']}Logré esto usando dos mapas y combinándolos, pero me gustaría usar solo un bucle si es posible.
EDITAR:
Actualmente estoy usando la desestructuración para extraer valores:
const mapOne = dd.map(({ keyone }) => keyone); const mapTwo = dd.map(({ two }) => two); const test = { keyone: mapOne, two: mapTwo, };Puede tomar una matriz de claves y agrupar los valores.
const data = [{ keyone: "test", two: "you", three: 'op' }, { keyone: "youuuu", two: "ttt", three: 'op' }, { keyone: "operation", two: "test", three: 'op' }], keys = ['keyone', 'two'], grouped = data.reduce((r, o) => { keys.forEach(k => (r[k] ??= []).push(o[k])); return r; }, {}); console.log(grouped);Una función implementada genéricamente, por lo tanto, reutilizable y configurable, que hace exactamente lo que pidió el OP, estaría cerca del siguiente código de ejemplo proporcionado ...
function groupAndCollectSpecifcEntriesOnly(collector, item) { const { keyList, result } = collector; keyList.forEach(key => { if (item.hasOwnProperty(key)) { (result[key] ??= []).push(item[key]) } }); return collector; } const sampleData = [{ keyone: "test", two: "you", three: 'op', }, { keyone: "youuuu", two: "ttt", three: 'op', }, { keyone: "operation", two: "test", three: 'op', }]; console.log( sampleData.reduce(groupAndCollectSpecifcEntriesOnly, { keyList: ['keyone', 'two'], result: {}, }).result ); console.log( sampleData.reduce(groupAndCollectSpecifcEntriesOnly, { keyList: ['three', 'keyone'], result: {}, }).result ); .as-console-wrapper { min-height: 100%!important; top: 0; }Puedes hacer algo como esto:
const dd = [ { keyone: "test", two: "you", three: 'op' }, { keyone: "youuuu", two: "ttt", three: 'op' }, { keyone: "operation", two: "test", three: 'op' }]; const result = dd.reduce((prev, acc, arr ) => { if (acc['keyone']) { prev['keyone'].push(acc['keyone']) } if (acc['two']) { prev['two'].push(acc['two']) } return prev; }, {keyone: [], two: []}); console.log(result);