How to return these values outside the Array?

Asked

Viewed 39 times

2

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

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

 prodadicional = ingrediente.ingrediente.nome;

 return prodadicional;

 })

alert(arrayAdicional);
  • What are you doing? Why does the Dictionary arrayget the return from the foreach?

  • Actually disregard this Dictionary array. Well I want to pass all the data from this foreach out of it, namely on a link to open on another page. If I write the link code inside it it will repeat all the values, and will create multiple links. I just want to put in a link all the returned values.

  • Ex: '<a id='btn-modal-ingredients' class='add-Cart btn-modal-ingredients' href='#dialog' data-add = ' + arrayAdicional + ' >Open</a>

2 answers

4


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

You can use it like this:

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

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

Undefined

1

With map is the best choice if you’re going to forEach could even be something like:

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

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

console.log(arrayAdicional);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.