3

I have an array of object products that received from server.

return response()->json(['products' => $products->toArray()]);

Here is its log:

enter image description here

And I need to loop through it to get the product.attributes that I think it's a array-like object, so I use Array.prototype.forEach.call

                this.products.forEach(product => {
                    console.log(product);
                    console.log(product.attributes);

                    Array.prototype.forEach.call(product.attributes, function(child) {
                        // It seems the loop doesn't work, so nothing is printed out.
                        console.log(child);
                    });
                });

But it seems the loop on array-like object didn't work, so nothing was printed out, even my product.attributes wasn't empty. Here is product.attributes log:

enter image description here

user3118789
  • 589
  • 2
  • 12
  • 26

2 Answers2

3

products.attributes is not an array like object, it is object.

But you can still iterate to that if you want. You just need to:

Object.entries(product.attribues).forEach(([key, value]) => {  })
2

Your product.attributes is also an Object. So Array.prototype.forEach.call doesn't work.

Try for...in statement:

for (var key in product.attributes) {
  console.log(product.attributes[key]);
}
AnhKhoa
  • 66
  • 4
  • Don't put url as an answer,because website contains may change in future so try to answer by reading website and mention that website as a reference. – Lakmi Apr 30 '19 at 04:46
  • 1
    @Lakmi thanks for reminding me. Edited my answer – AnhKhoa Apr 30 '19 at 04:53