Create array of objects based on another array?
Posted
by
xckpd7
on Stack Overflow
See other posts from Stack Overflow
or by xckpd7
Published on 2012-09-14T15:09:32Z
Indexed on
2012/09/14
15:38 UTC
Read the original article
Hit count: 567
JavaScript
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?
© Stack Overflow or respective owner