how to do push array inside an object that is in an array?

1

I'm trying to create a JSON and I need to do the following:

var arreglo = [];

var sumar = () => {
    var id = arreglo.length + 1; 

    arreglo.push({id: id});

    console.log('Arreglo', arreglo)
};

sumar();

as Result prints: Arreglo [ { id: 1 } ] .

Suppose that I execute the function twice for the example and
would have this array: [ { id: 1 }, { id: 2 } ] .

What I want to achieve is to be able to add an array to where the id: 1

is

or the id that goes generating, achieved that is as follows:

[ {"id": 1 ,
"preguntas":[{
    "idp":1,
    "preg": "¿como estás?"
},{
   "idp":2,
   "preg": "it is important make my laptop?"
}]}, 
  { "id": 2,
"preguntas":[{
    "idp":1,
    "preg": "¿como estás?"
},{
    "idp":2,
    "preg": "it is important make my laptop?"
}]} 

]

I know first what to fill another arrangement:

  var sumarAobj = () => {
  var id = arregloInterno.length + 1;

  arregloInterno.push({
  id: id,
  pregunta: '¿como estás?'
});

...

};

How should I continue? I tried with push and splice but does not want to.

Thank you.

    
asked by Hernan Humaña 18.08.2017 в 21:35
source

1 answer

3

If I understood correctly, what you want is to have an array of objects, where each object has an array and that array adds elements.

Access the indece of each element in the array and then the property that has the array and add it with .push() :

var data = [];
data.push({id:1, preguntas: []});
data[0].preguntas.push({idp: 1, preg: "¿Que dia es hoy?"});
data[0].preguntas.push({idp: 2, preg: "¿Esta frio fuera?"});

console.log(data);

Here is an example of agreating elements with a for:

var data = [];
   for(var i = 3; i < 10; i++)
   {
   
         data.push({ id:i, preg:[] });
         data[data.length-1].preg.push( {pid: i, preg: "Aqui pregunta" });
   }

console.log(data);
    
answered by 18.08.2017 / 22:31
source