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

142
Visualizações
How to join javascript array elements without forloop

I have from a mongoose query result:

{
    "store": [
        {
            "items": [
                "A1",
                "A2"
            ]
        },
        {
            "items": [
                "A3",
                "A4"
            ]
        },
        {
            "items": [
                "B1",
                "B2"
            ]
        },
        {
            "items": [
                "B3",
                "B4"
            ]
        },
        {
            "items": [
                "C8",
                "C9",
                "C10"
            ]
        }
    ]
}

I need this: ["A1","A2","A3","A4","B1","B2","B3","B4","C8","C9",C10] Is there any way to do this without using foreach loop, as my array will be so long and it will be time consuming.

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

0

let data = {
  'store': [
    {
      'items': [
        'A1',
        'A2'
      ]
    },
    {
      'items': [
        'A3',
        'A4'
      ]
    },
    {
      'items': [
        'B1',
        'B2'
      ]
    },
    {
      'items': [
        'B3',
        'B4'
      ]
    },
    {
      'items': [
        'C8',
        'C9',
        'C10'
      ]
    }
  ]
}

let result = data['store'].flatMap(value => value.items)

console.log(result)

about 4 years ago · Juan Pablo Isaza Relatório

0

To boost the performance even more you can directly use an aggregation to make use of the faster C++ performing in the database:

I am assuming your database document looks something like this: enter image description here

If you use an aggregation like this:

let result = Model.aggregate([
  {'$match':{'_id': "YourDesiredId"}}, // Add this line in case you want to match a specific document
  {
    '$unwind': {
      'path': '$store'
    }
  }, {
    '$unwind': {
      'path': '$store.items'
    }
  }, {
    '$group': {
      '_id': '$_id', 
      'items': {
        '$push': '$store.items'
      }
    }
  }, {
    '$project': {
      '_id': 0
    }
  }
])

Your output will be:

items:["A1","A2","A3","A4","B1","B2","B3","B4","C8","C9","C10"]
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