const array = [{ "id": "1", "main": [{ "type": "a", "nu": '0', "role": 1 }], }, { "id": "2", "main": [{ "type": "b", "nu": '0', "role": 2 }], }, { "id": "3", "main": [{ "type": "c", "nu": '0', "role": 2 }], }, { "id": "4", "main": [{ "type": "d", "nu": '0', "role": 2 }], }]Desde el objeto anterior, quiero combinar id-2,3 y 4 en una clave que tiene 3 objetos.
const result = [array.reduce((acc, {id, main}) => { const { nu, role, type } = main[0] const hash = `${nu}-${role}`; acc[hash] = acc[hash] ? [{ ...acc[hash] }, {type: type, id: id }] : { type, id: [id] }; return acc; }, {})];Ejemplo:
const array = [{ "id": "1", "main": [{ "type": "a", "nu": '0', "role": 1 }], }, { "id": "2", "main": [{ "type": "b", "nu": '0', "role": 2 }], }, { "id": "3", "main": [{ "type": "c", "nu": '0', "role": 2 }], }, { "id": "4", "main": [{ "type": "d", "nu": '0', "role": 2 }], }] const result = [array.reduce((acc, {id, main}) => { const { nu, role, type } = main[0] const hash = `${nu}-${role}`; acc[hash] = acc[hash] ? [{ ...acc[hash] }, {type: type, id: id }] : { type, id: [id] }; return acc; }, {})]; console.log(result);No estoy seguro de dónde me estoy equivocando, ¿alguien puede ayudarme?
Podría reducir las matrices con un objeto y una clave común con ceros rellenos al principio.
const data = [{ id: "1", main: [{ type: "a", nu: "0", role: 1 }] }, { id: "2", main: [{ type: "b", nu: "0", role: 2 }] }, { id: "3", main: [{ type: "c", nu: "0", role: 2 }] }, { id: "4", main: [{ type: "d", nu: "0", role: 2 }] }], result = data.reduce((r, { id, main }) => { main.forEach(({ type, nu, role }) => { const key = `${nu.toString().padStart(3, 0)}-${role}`; (r[key] ??= []).push({ id, type }); }); return r; }, {}); console.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; } Para obtener un resultado exacto, como en la imagen, puede envolver la id del primer objeto de un grupo en una matriz y, si un grupo tiene más de un objeto, tome una matriz.
const data = [{ id: "1", main: [{ type: "a", nu: "0", role: 1 }] }, { id: "2", main: [{ type: "b", nu: "0", role: 2 }] }, { id: "3", main: [{ type: "c", nu: "0", role: 2 }] }, { id: "4", main: [{ type: "d", nu: "0", role: 2 }] }], result = data.reduce((r, { id, main }) => { main.forEach(({ type, nu, role }) => { const key = `${nu.toString().padStart(3, 0)}-${role}`; r[key] = r[key] ? [].concat(r[key], { id, type }) : { id: [id], type }; }); return r; }, {}); console.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; }