Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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???