Home > Mobile >  How to insert an array inside another array?
How to insert an array inside another array?

Time:11-24

I have an array called "pedidos" which the length is x because it depends on the amount of "orders" we get this get's updated automatically through firebase.

each "order" has the following attributes:

acudiente: ""
banco: "Global Bank"
data: (12) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
email: ""
escuela: "Academia Internacional David"
estadoDeDisponibilidad: "Pendiente"
estadoDePago: "Pendiente"
fecha: "11/22/2021"
grado: "1° Grado"
id: "[AID]PM-345"
identificacion: ""
metodoDePago: "ACH"
nombre: "Brihana Orisiveth De Gracia Concepción "
phone: ""
total: "346.45"
totalPagado: 0
uid: "13eLyFqGGrZ0vTu3llpVxeFCBun2"

Now, each order has an attribute called "data" which is x because people can order x amount of stuff so 12 is not a constant. Each item inside data has the following attributes:

descripcion: "ACCELIUM - Programa de Tecnología"
disponible: 0
editorial: "Programa"
grado: (6) ['1° Grado', '2° Grado', '3° Grado', '4° Grado', '5° Grado', '6° Grado']
id: "L-25304"
materia: "Tecnologia"
ordenados: 12
precio: "35.00"
tipo: "Programa"

Now I'm trying to make a NEW Array that will contain every data array, which means that if there are 5 orders with 5 items each it should be an array of 25, this is a very simple for loop:

for(let x = 0; x < pedidos.length; x  ){
      for(let y = 0; y < pedidos[x].data.length; y  ){
        pedidosExcel.push(pedidos[x].data[y])
      }
    }

however I also want some attributes from the main array and not just the attributes from the array called "data", so I wanted to know if it was possible to MERGE attributes from each other.

Update

So I wasn't able to do what I wanted but I manage to get close to it with the following piece of code, however if I do this it ends up as an array inside an array for some reason. I manually set up every attribute because I wanted to overwrite some of them since some attributes have the same name

for(let x = 0; x < pedidos.length; x  ){
      for(let y = 0; y < pedidos[x].data.length; y  ){
        pedidosExcel.push(pedidos[x].data[y])
        pedidosExcel[y] = [{
          id: pedidos[x].id,
          nombre: pedidos[x].nombre,
          escuela: pedidos[x].escuela,
          grado: pedidos[x].grado,
          fecha: pedidos[x].fecha,
          descripcion: pedidos[x].data[y].descripcion,
          tipo: pedidos[x].data[y].tipo,
          editorial: pedidos[x].data[y].editorial,
          precio: pedidos[x].data[y].precio,
        }]
      }
    }

Hope this is more clear than my previous explanation.

CodePudding user response:

The problem is you're producing a nested array, but you want it to be flat. You have a couple of options:

Option 1: Use .flatMap():

This function is simply a combination of .map() and .flat()

const pedidos = [{
  id: '[AID]PM-345',
  nombre: '999999990',
  escuela: 'ABCDEF',
  grado: '1° grado ',
  fecha: '11/22/2021',
  data: [
    {
      descripcion: 'ACCELIUM - Programa',
      tipo: 'Programa',
      editorial: 'Programa',
      precio: '35.00'
    },
    {
      descripcion: 'ACCELIUM - Programa 2',
      tipo: 'Programa 2',
      editorial: 'Programa 2',
      precio: '45.00'
    }
  ]
}];

const pedidosExcel = pedidos.flatMap(pedido =>
  pedido.data.map(item => ({
    id: pedido.id,
    nombre: pedido.nombre,
    escuela: pedido.escuela,
    grado: pedido.grado,
    fecha: pedido.fecha,
    descripcion: item.descripcion,
    tipo: item.tipo,
    editorial: item.editorial,
    precio: item.precio
  }))
);

console.log(pedidosExcel);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Option 2 Use .reduce():

This function has the advantage of being used more widely than .flatMap() so may be more understandable. Maybe.

Reduce iterates through an array, and passes a value from one iteration to the next (acc in my example).

const pedidos = [{
  id: '[AID]PM-345',
  nombre: '999999990',
  escuela: 'ABCDEF',
  grado: '1° grado ',
  fecha: '11/22/2021',
  data: [
    {
      descripcion: 'ACCELIUM - Programa',
      tipo: 'Programa',
      editorial: 'Programa',
      precio: '35.00'
    },
    {
      descripcion: 'ACCELIUM - Programa 2',
      tipo: 'Programa 2',
      editorial: 'Programa 2',
      precio: '45.00'
    }
  ]
}];

const pedidosExcel = pedidos.reduce((acc, pedido) =>
  [
    ...acc,
    ...pedido.data.map(item => ({
      id: pedido.id,
      nombre: pedido.nombre,
      escuela: pedido.escuela,
      grado: pedido.grado,
      fecha: pedido.fecha,
      descripcion: item.descripcion,
      tipo: item.tipo,
      editorial: item.editorial,
      precio: item.precio
    }))
  ],
[]); 

console.log(pedidosExcel)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Use whichever you think is easiest and most understandable to your team.

Thank you for adding code to your question - next time please add the expected outcome and data as code as well.

CodePudding user response:

As far as I see you have an array with object inside it (not arrays), and inside this object you have many different keys, one of this keys is data, which is array with other objects. So what data model you want to get? Describe it in small example.

  • Related