Sand Eep
Sand Eep

Reputation: 41

Javascript outputting array values

Can't really figure out why I cant get the values that I have passed through an AJAX call in my javascript function.

As seen in the picture, msg is the array that's passed from the backend to the javascript function I've tried both

info['taxarray'].forEach() and info.taxarray.forEach() 

Console.log(info.taxarray) works fine and it outputs the array in the console, but when I try to run iterations through this array, I can't access the values in it, I'm sure I'm missing something, but I can't figure out what it is.

This is the output for the console

Upvotes: 1

Views: 122

Answers (3)

Abd-Elaziz Sharaf
Abd-Elaziz Sharaf

Reputation: 334

the response you get seems to be multidimensional (an array of arrays each of which has only one element)

info.taxarray.forEach(msg) { (item) => {
    console.log(item[0].tax_values)
}};

OR if array elements can be more so iterate again

info.taxarray.forEach(msg) { (item) => {
    item.forEach(msg) { (item) => {
        console.log(i.tax_values)
    }};
}};

Upvotes: 1

Mike Ezzati
Mike Ezzati

Reputation: 3166

You can flatten the multidimensional array with flat method:

info.flat().forEach(item => console.log(item.tax))

Using flatmap it gets even more straightforward

info.flatMap(item => console.log(item.tax))

Upvotes: 5

sohaieb azaiez
sohaieb azaiez

Reputation: 780

As i can see, your info.taxarray is a multidementional array so that's every element inside it is also an another array.
your console.log(info.taxarray) gives see :

[Array(1), Array(1)]

to access tax_values of the first element you have to write info.taxarray[0][0].tax_values so that means you have to iterate the taxarray and also it's elements (which are arrays too) .
Check your code. you can also refer to the solution of Mike Ezzati it help a lot

Upvotes: 3

Related Questions