Reputation: 3767
I want to take an array like this:
var food = [
{
name: 'strawberry',
type: 'fruit',
color: 'red',
id: 3483
},
{
name: 'apple',
type: 'fruit',
color: 'red',
id: 3418
},
{
name: 'banana',
type: 'fruit',
color: 'yellow',
id: 3458
},
{
name: 'brocolli',
type: 'vegetable',
color: 'green',
id: 1458
},
{
name: 'steak',
type: 'meat',
color: 'brown',
id: 2458
},
]
And I want to create something like this dynamically:
var foodCategories = [
{
name: 'fruit',
items: [
{
name: 'apple',
type: 'fruit',
color: 'red',
id: 3418
},
{
name: 'banana',
type: 'fruit',
color: 'yellow',
id: 3458
}
]
},
{
name: 'vegetable',
items: [
{
name: 'brocolli',
type: 'vegetable',
color: 'green',
id: 1458
},
]
},
{
name: 'meat',
items: [
{
name: 'steak',
type: 'meat',
color: 'brown',
id: 2458
}
]
}
]
What's the best way to go about doing this?
Upvotes: 0
Views: 643
Reputation: 707218
You can do it like this. You iterate through the food array and for each object you find, you look in the foodCategories array and see if you have an object for that food type. If you don't, you add one. Then, you add the food item to the right category object's array.
var foodCategories = [];
function findTypeInArray(arr, type) {
for (var i = 0; i < arr.length; i++) {
if (arr[i].name === type) {
return(i);
}
}
return(-1);
}
for (var i = 0; i < food.length; i++) {
var item = food[i];
var index = findTypeInArray(foodCategories, item.type);
if (index === -1) {
foodCategories.push({name: item.type, items: []});
index = foodCategories.length - 1;
}
foodCategories[index].items.push(item);
}
Working demo: http://jsfiddle.net/jfriend00/CwEE7/
Upvotes: 2