¿Cómo puedo extraer elementos de una matriz dentro de una matriz a esta matriz?
Lo que tengo es esto:
const tableData = [ { display: '2022-03', column: 'data', detailList: [ { title: 'Quantity', value: 1, sourceId: null, }, { title: 'Price', value: 2, sourceId: null, }, { title: 'Weight', value: 3, sourceId: null, }, { title: 'income', value: 4, sourceId: null, }, ], }, { display: '2022-02', column: 'data', detailList: [ { title: 'Quantity', value: 7, sourceId: null, }, { title: 'Price', value: 6, sourceId: null, }, { title: 'Weight', value: 5, sourceId: null, }, { title: 'income', value: 4, sourceId: null, }, ], }, ];Ahora quiero que se convierta en esto:
res = [ { title: '2022-03', 'Quantity': '1', 'Price': '2', 'Weight': '3', 'income': '4', }, { title: '2022-02', 'Quantity': '7', 'Price': '6', 'Weight': '5', 'income': '4', }, ];¿Cuál es la mejor manera de hacerlo?
Estoy tratando de crear una nueva matriz afuera y uso dos .map() para hacerlo. Pero parece que no se puede leer.
¿Puede alguien darme una mejor solución que use algunas características de ES6 que lo hagan parecer más legible?
Debe asignar el resultado de map() directamente a res , en lugar de llamar a push() dentro del mapa.
Puede usar Object.fromEntries() para crear el objeto desde el mapa interno.
La desestructuración y la sintaxis extendida pueden simplificar la forma en que accede a las propiedades y crea el objeto resultante.
const tableData = [{ display: '2022-03', column: 'data', detailList: [{ title: 'Quantity', value: 1, sourceId: null, }, { title: 'Price', value: 2, sourceId: null, }, { title: 'Weight', value: 3, sourceId: null, }, { title: 'income', value: 4, sourceId: null, }, ], }, { display: '2022-02', column: 'data', detailList: [{ title: 'Quantity', value: 7, sourceId: null, }, { title: 'Price', value: 6, sourceId: null, }, { title: 'Weight', value: 5, sourceId: null, }, { title: 'income', value: 4, sourceId: null, }, ], }, ]; let res = tableData.map(({ display, detailList }) => ({ title: display, ...Object.fromEntries(detailList.map(({ title, value }) => [title, value === null ? '-' : value])) })); console.log(res);const res = tableData.map(({ display, detailList}) => { const obj = { title: display, } detailList.forEach(el => obj[el.title] = el.value); return obj; })Esta puede ser una posible solución para lograr el objetivo deseado.
Fragmento de código
const transformArray = arr => arr.map( // iterate using "map" ({display : title, detailList}) => ({ // de-structure, and rename title, ...( detailList.reduce( // iterate using "reduce" (fin, {title, value}) => ({ // de-structure to access title, value ...fin, [title]: value // may add "value" is null check here }), {} // the "fin" object is initialized to empty ) ) }) ); const tableData = [ { display: '2022-03', column: 'data', detailList: [ { title: 'Quantity', value: 1, sourceId: null, }, { title: 'Price', value: 2, sourceId: null, }, { title: 'Weight', value: 3, sourceId: null, }, { title: 'income', value: 4, sourceId: null, }, ], }, { display: '2022-02', column: 'data', detailList: [ { title: 'Quantity', value: 7, sourceId: null, }, { title: 'Price', value: 6, sourceId: null, }, { title: 'Weight', value: 5, sourceId: null, }, { title: 'income', value: 4, sourceId: null, }, ], }, ]; console.log(transformArray(tableData)); .as-console-wrapper { max-height: 100% !important; top: 0; }Explicación
Los comentarios en línea explican los pasos involucrados.
NOTAS
Esta solución utiliza:
.reduce()display se renombra como title... difundir para realizar una copia superficial