Tengo una serie de documentos:
[{ "name": "AAPL", "ownerTotals": {uid: "xxx", totaledAmount: 140 }, {uid: "yyy", totaledAmount: 10} }, { "name": "TSLA", "ownerTotals": {uid: "xxx", totaledAmount: 11 }, {uid: "yyy", totaledAmount: 2} }]y una serie de propietarios:
{uid: "xxx"}, {uid: "yyy"}Estoy tratando de crear un nuevo/(actualizar) el objeto de los propietarios con un objeto anidado que contiene las posiciones que poseen. entonces quiero actualizar los propietarios a este formato:
[{uid: "xxx", "positions": [{name: "AAPL", totaledAmount: 140 },{name: "TSLA", totaledAmount: 11}] }, {uid: "yyy", "positions": [{name: "AAPL", totaledAmount: 10 },{name: "TSLA", totaledAmount: 2}] }]¿Cuál es la mejor manera de lograr esto?
Yo estaba tratando de algo a lo largo de las líneas de
owners.forEach((owner) => { documents.forEach((document) => { document.ownerTotals.forEach((ownerTotal) => { if (ownerTotal.uid === owner.uid) { } } }) } })No estoy realmente seguro de qué hacer en el corazón de cada ciclo, y ni siquiera estoy seguro de si ForEach es la forma más metódica para esto... Estoy usando reacción moderna con ganchos.
Puedes hacer algo como esto:
const documents = [ { name: "AAPL", ownerTotals: [ { uid: "xxx", totaledAmount: 140 }, { uid: "yyy", totaledAmount: 10 } ] }, { name: "TSLA", ownerTotals: [ { uid: "xxx", totaledAmount: 11 }, { uid: "yyy", totaledAmount: 2 } ] } ]; const owners = [{ uid: "xxx" }, { uid: "yyy" }]; const res = owners.map(({ uid }) => { let ownedDocuments = []; documents.forEach((doc) => { let docFound = doc.ownerTotals.find(({ uid: docUid }) => docUid === uid); if (docFound) { ownedDocuments.push({ name: doc.name, totaledAmount: docFound.totaledAmount }); } }); return { uid, positions: ownedDocuments }; }); console.log(res);Puede usar reduce para agrupar posiciones por ID de userid .
const positions = [{ "name": "AAPL", "ownerTotals": {uid: "xxx", totaledAmount: 140 }, {uid: "yyy", totaledAmount: 10} }, { "name": "TSLA", "ownerTotals": {uid: "xxx", totaledAmount: 11 }, {uid: "yyy", totaledAmount: 2} }] const posByUid = positions.reduce((acc, current) => { const name = current.name current.positions.forEach(position => { if (!acc[position.uid]) { acc[position.uid] = [] } acc[position.uid] = {name, totaledAmount: position.totaledAmount} }) return acc }, {})