Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Create an Array of Objects

Chris Grazioli
Chris Grazioli
31,225 Points

Cant get "For In" loop to work for Create an Array of Objects

// 1. Create an array named products.
let products =[
  {
  name: "Blue Rubber Ducky",
  inventory: 2,
  unit_price:5.99
  },
  {
  name: "Red Rubber Ducky",
  inventory: 3,
  unit_price:4.99
  },
  {
  name: "Black Rubber Ducky",
  inventory: 4,
  unit_price:6.99
  },
  {
  name: "Purple Rubber Ducky",
  inventory: 5,
  unit_price: 2.97
  }

];

function listProducts(prods){
  let names =[];
  //for(item in prods){
  //  names.push(item.name);
  //}
  for(let i=0 ; i<prods.length ; i++){
   names.push(prods[i].name); 
  }
  return names;
}

console.log(listProducts(products));

Why can'tI get this for/in syntax to work?

1 Answer

Chris Grazioli
Chris Grazioli
31,225 Points

SOLVED - Got it, was missing the reference to prods

function listProducts(prods){
  let names =[];
  for(item in prods){
    names.push(prods[item].name);
  }
  return names;
}
Chris Grazioli
Chris Grazioli
31,225 Points

Come to think of it though, ANYONE know what the difference between a for/in and for/of loop is/are???