-1

I've searched a bunch of Javascript tutorials but there are too many simple ones making it hard to find a detailed one that answers my question. I have an array that looks like this:

var food = [
    ['apple', 'strawberry', 'orange'],
    ['carrots', 'beans', 'peas'],
    ['cookies', 'cake', 'muffins', 'pie'] 
];

I want to be able to loop through each of these items by category looking for a specific value. Something like this would be nice:

for (var i in food.fruit) {
  if(food.fruit[i] == "apple") {
    console.log("Found "+food.fruit[i]);
  }
}

But I don't know how to setup the array so I can reference it by category. The following just throws an error about the colon.

    var food = [
      fruit: ['apple', 'strawberry', 'orange'],
      veggies: ['carrots', 'beans', 'peas'],
      sweets: ['cookies', 'cake', 'muffins', 'pie'] 
    ];

I'm asking because later I'll want even more complex categories like food.fruit.color or something and need it all in one array so I can easily reference the values I need. Thanks.

Thread7
  • 1,081
  • 2
  • 14
  • 28
  • 3
    You need an object, not an array – adeneo Jan 04 '16 at 23:06
  • Unrelated side note: [don't use `for .. in` to loop through arrays](http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea). – JJJ Jan 04 '16 at 23:10

1 Answers1

3
var food = {
  fruit: ['apple', 'strawberry', 'orange'],
  veggies: ['carrots', 'beans', 'peas'],
  sweets: ['cookies', 'cake', 'muffins', 'pie'] 
};
Davide Ungari
  • 1,920
  • 1
  • 13
  • 24