无法循环遍历类数组对象。

3

我有一个从服务器接收到的对象产品数组。

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

这是它的日志:

enter image description here

我需要循环遍历它以获取我认为是类似数组的对象product.attributes,因此我使用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);
                    });
                });

但是似乎对类数组对象的循环不起作用,因此没有打印出任何内容,即使我的product.attributes也不为空。这是product.attributes日志:

enter image description here


这个 -> 符号是什么意思?看起来不像 JavaScript? - Steve Bennett
that's from Laravel - user3118789
Object.keys [MDN, spec] — 该函数提供了一个数组,其中包含对象自身的可枚举属性名称(字符串类型)。Object.values [MDN, spec] — 该函数提供了一个数组,其中包含对象自身的可枚举属性值。 - Murtaza Hussain
2个回答

3

products.attributes 不是一个类似数组的对象,它是一个对象。

但如果您愿意,仍然可以对其进行迭代。您只需要:

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

2
你的产品属性 product.attributes 也是一个对象,所以 Array.prototype.forEach.call 不起作用。
尝试使用 for...in 语句
for (var key in product.attributes) {
  console.log(product.attributes[key]);
}

请不要将网址作为答案,因为网站内容可能会在未来发生变化,请通过阅读网站并提及该网站作为参考来回答问题。 - Lakmi
1
@Lakmi 谢谢你提醒我。我已经编辑了我的回答。 - AnhKhoa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接