1
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');
      }
      } ;

I am able to view the result but why does it show an array full of undefined items. o/p for y :

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

jps
  • 20,041
  • 15
  • 75
  • 79
  • What kind of data is inside products? can you attach a `console.log(products)`. – nabroleonx Jan 27 '22 at 07:38
  • basically its an array : Array(15) 0: {id: '2', name: 'Baseball', description: 'PRODUCT''} 1: {id: '13', name: 'Hat', description: 'PRODUCT'} 2: {id: '8', name: 'Cardio', description: 'Activity''} 3: {id: '9', name: 'Weight Training ', description: 'Activity''}... and so on – Damon Holmes Jan 27 '22 at 07:50

1 Answers1

0

Its a bad idea to use for...in for looping, you can map the values instead of using a for...in or just use regular loop.

if (products){
    products.map((x) => y.push(x.name));
}
nabroleonx
  • 96
  • 5
  • Hey thank you so much man.. it worked !!! could you please tell me what went wrong while using a for-loop ? – Damon Holmes Jan 27 '22 at 08:12
  • you can use regular for loop and it should be fine, but u used `for...in` which is not recommended for looping through arrays or array-like objects in your case, you can find why this is the case in this [SO](https://stackoverflow.com/questions/500504/why-is-using-for-in-for-array-iteration-a-bad-idea). Throw me an upvote, if you find it useful. :) – nabroleonx Jan 27 '22 at 08:18
  • i really want to for sure.. this is my first question on stackoverflow .. theres's something called 15 reputation before i can make any upvotes .. thanks again for your help !!! – Damon Holmes Jan 27 '22 at 08:21