Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

141
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda