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

3
  • What is this -> notation? Doesn't look like javascript? Commented Apr 30, 2019 at 4:22
  • that's from Laravel Commented Apr 30, 2019 at 4:24
  • Object.keys [MDN, spec] — A function providing an array of the names of an object's own, enumerable properties whose names are strings. Object.values [MDN, spec] — A function providing an array of the values of an object's own, enumerable properties. Commented Apr 30, 2019 at 4:28

2 Answers 2

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]) => {  })
Sign up to request clarification or add additional context in comments.

Comments

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]);
}

2 Comments

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 thanks for reminding me. Edited my answer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.