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

261
Visualizações
How to group nested array of objects in js

I have a nested array of objects. I'm trying to group product objects that have the same value.

Each objects has a vendor property containing an email. I am trying to group the objects by matching vendor email

This is how my database looks like:

[
        {
            _id: "622d70a49bd88b1599026318",
            products: [
                {
                    _id: "6223186e2278d4e502f5264a",
                    title: "Product number 1",
                    price: 600,
                    cartQuantity: 1,
                    vendor: {email: "vendor1@gmail.com"}
                },
                {
                    _id: "622d4e9f9bd88b1599026317",
                    title: "asdas",
                    price: 100,
                    cartQuantity: 5,
                    vendor: {
                        email: "vendor2@gmail.com"
                    }
                },
                 {
                    _id: "622d4e9f9bd88b1599026317",
                    title: "asdas",
                    price: 100,
                    cartQuantity: 5,
                    vendor: {
                        email: "vendor2@gmail.com"
                    }
                }
            ]
        }]

I am trying to do it with the reduce method but the problem is with using map inside the reduce. It repeats the object many times. I am also unable to get the grouped objects.

const groupedMap = db.reduce(
    (entryMap, e) => e.products.map((product) => entryMap.set(product.vendor.email, [...entryMap.get(product)||[], product])),
    new Map()
);

The above code output is: enter image description here

My expectation is:

[0: {"vendor1@gmail.com" => Array(1)}
   key: "vendor1@gmail.com"
   value: [{_id: '6223186e2278d4e502f5264a', title: 'Product number 1', price: 600, cartQuantity: 1, vendor: {email: "vendor1@gmail.com"}}],
1: {"vendor2@gmail.com" => Array(2)}
key: "vendor2@gmail.com"
   value: [{_id: '6223186e2278d4e502f5264a', title: 'Product number 1', price: 600, cartQuantity: 1, vendor: {email: "vendor2@gmail.com"}},
{_id: '6223186e2278d4e502f5264a', title: 'Product number 1', price: 600, cartQuantity: 1, vendor: {email:"vendor2@gmail.com"}}
]
]

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

0

Loop through each item in the array and see if the vendor email exists as a key already in a dictionary, if it exists push it to that array, otherwise set the value of the vendor email key equal to an array with the current item in it

See code below

const data = [{
  _id: "622d70a49bd88b1599026318",
  products: [{
      _id: "6223186e2278d4e502f5264a",
      title: "Product number 1",
      price: 600,
      cartQuantity: 1,
      vendor: {
        email: "vendor1@gmail.com"
      }
    },
    {
      _id: "622d4e9f9bd88b1599026317",
      title: "asdas",
      price: 100,
      cartQuantity: 5,
      vendor: {
        email: "vendor2@gmail.com"
      }
    },
    {
      _id: "622d4e9f9bd88b1599026317",
      title: "asdas",
      price: 100,
      cartQuantity: 5,
      vendor: {
        email: "vendor2@gmail.com"
      }
    }
  ]
}];

const mapped = {};
data[0].products.forEach(item => {
  if (item.vendor.email in mapped) return mapped[item.vendor.email].push(item);

  mapped[item.vendor.email] = [item];
});

const expectedFormat = Object.keys(mapped).map(key => {
  const o = {};
  o[key] = mapped[key];
  
  return o;
});

console.log(expectedFormat)

about 4 years ago · Juan Pablo Isaza Relatório

0

try to make an object where key is the value you group by. the next step is foreach in which you check each object in the array, whether the value you are looking for is in the object made - if not, then you filter the array by searched value and add the result to your object

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