How to return these values outside the Array?

2

How do I get all the values that are inside this foreach and show off it? It only takes the last one when I give ALERT:

var arrayAdicional = item.ingrediente_adicional.forEach(function(ingrediente)
{

 prodadicional = ingrediente.ingrediente.nome;

 return prodadicional;

 })

alert(arrayAdicional);
    
asked by anonymous 13.07.2017 / 22:47

2 answers

4

It seems to me that you want to map the values, and for this there is .map() that creates a new array with the return of each loop iteration that .map() creates.

You can use this:

var arrayAdicional = item.ingrediente_adicional.map(function(ingrediente){
     return ingrediente.ingrediente.nome;    
});

alert(JSON.stringify(arrayAdicional, null, 4))

undefined

    
13.07.2017 / 22:49
1
___ erkimt ___ How to return these values outside the Array? ______ qstntxt ___

How do I get all the values that are inside this foreach and show off it? It only takes the last one when I give ALERT:

var arrayAdicional = [];
item.ingrediente_adicional.forEach(function(ingrediente){

    arrayAdicional.push(ingrediente.ingrediente.nome);
})

console.log(arrayAdicional);
    
______ azszpr220309 ___

It seems to me that you want to map the values, and for this there is map that creates a new array with the return of each loop iteration that forEach creates.

You can use this:

var arrayAdicional = [];
item.ingrediente_adicional.forEach(function(ingrediente){

    arrayAdicional.push(ingrediente.ingrediente.nome);
})

console.log(arrayAdicional);

undefined

    
______ ___ azszpr220310

%code% is the best choice, if it is followed by the %code% same could be something like:

%pre%     
___
13.07.2017 / 22:51