无法使用从 graphql 获取的数据

Can't use data fetched from graphql

const Products = async()=> {
    try {
      const result= await API.graphql(graphqlOperation(listProducts));
      const products = result.data.listProducts.items;
      console.log(products);
      let y = []
      if (products){
       for (let x in products){
       y.push(x.name);
       }
      }
      console.log(y);
  
     } catch (err) { 
      console.log('error fetching products');
      }
      } ;

我可以查看结果,但为什么它会显示一个充满未定义项的数组。 o/p y :

[undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined]

使用 for...in 循环不是个好主意,您可以映射值而不是使用 for...in 或只使用常规循环。

if (products){
    products.map((x) => y.push(x.name));
}