Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

107
Visualizações
React looping and creating new array with nested objects

I have an array of documents:

    [{
      "name": "AAPL",
      "ownerTotals": {uid: "xxx", totaledAmount: 140 }, {uid: "yyy", totaledAmount: 10}
    },
    {
      "name": "TSLA",
      "ownerTotals": {uid: "xxx", totaledAmount: 11 }, {uid: "yyy", totaledAmount: 2}
    }]

and an array of owners:

{uid: "xxx"}, {uid: "yyy"}

I'm trying to create a new/(update) the owners object with a nested object that contains the positions they own. so I want to update owners to this format:

    [{uid: "xxx", "positions": [{name: "AAPL", totaledAmount: 140 },{name: "TSLA", totaledAmount: 11}] },
    {uid: "yyy", "positions": [{name: "AAPL", totaledAmount: 10 },{name: "TSLA", totaledAmount: 2}] }]

what's the best way to achieve this?

I was trying for something along the lines of

owners.forEach((owner) => {
        documents.forEach((document) => {
           document.ownerTotals.forEach((ownerTotal) => {
                if (ownerTotal.uid === owner.uid) {

                 }
             }
        })
     }
})

Not really sure what to do at the heart of each loop, and not even sure if ForEach is the most method way for this...I'm using modern react with hooks.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can do something like this:

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);

about 4 years ago · Juan Pablo Isaza Relatório

0

You can use reduce to group positions by 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
}, {})
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda