我想采用这样的数组:
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
},
]
我想动态地创建这样的东西:
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
}
]
}
]
这样做最好的方法是什么?
答案 0 :(得分:1)
你可以这样做。您遍历食物数组,并找到您找到的每个对象,查看foodCategories数组,看看您是否有该食物类型的对象。如果不这样做,则添加一个。然后,将食物项添加到右侧类别对象的数组中。
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);
}