After days of hairpulling, I decided to seek help:
I have an array of objects, one for each grocery store item. Each object has 3 properties: category (string for category of item), itemName (string for item itself), and onSale (boolean whether it's on sale or not):
var itemData = [ { category: 'fruit', itemName: 'apple', onSale: false }, { category: 'canned', itemName: 'beans', onSale: false }, { category: 'canned', itemName: 'corn', onSale: true }, { category: 'frozen', itemName: 'pizza', onSale: false }, { category: 'fruit', itemName: 'melon', onSale: true }, { category: 'canned', itemName: 'soup', onSale: false }, ];
I need to convert it into an object whose properties are the object categories. Each property is an array containing values in itemName that correspond to the property:
{ fruit: ['apple', 'melon($)'], canned: ['beans', 'corn($)', 'soup'], frozen: ['pizza'] };
When I try to do it, I end up with directionally correct values, except they're repeated:
{ fruit: [ 'apple', 'apple', 'melon', 'melon', 'melon' ], canned: [ 'beans', 'beans', 'corn', 'corn', 'corn', 'soup', 'soup', 'soup' ], frozen: [ 'pizza', 'pizza' ] }
I spent hours trying to find out where I went wrong, to no avail. Here's my code:
function organizeItems (array){ //create output obj var output = {} //iterate over the array for(var i = 0; i < array.length; i++){ //iterate over the object in the array for(var category in array[i]){ //if value of category isn't in output add the value to output as an empty array if(output[array[i]["category"]] === undefined){ output[array[i]["category"]] = []; //if not --> push the itemName to the category } else{ output[array[i]["category"]].push(array[i]["itemName"]) } } } return output }
How can I avoid the repetition and end up with the correct values in the arrays?