js数组分类

原始数据类型:

let test = [
  {id: "7", city: "全部", name: "稀饭"},
{id: "6", city: "全部", name: "米饭"},
{id: "1", city: "重庆", name: "火锅"},
{id: "2", city: "江苏", name: "肥肠粉"},
{id: "3", city: "重庆", name: "小面"},
{id: "4", city: "北京", name: "北京烤鸭"},
{id: "5", city: "北京", name: "酸辣粉"}

]

期望转换成:

var correct = [
{    city:"全部",
info:{
{id:'6',name:'米饭'},
{id:'7',name:'稀饭'},
}
},
{city:"重庆",
info:{
{id:'1',name:'火锅'},
{id:'3',name:'小面'},
}
},
{city:"北京",
info:{
{id:'4',name:'北京烤鸭'},
{id:'5',name:'酸辣粉'},
}
},
{city:"江苏",
info:{
{id:'2',name:'肥肠粉'},
}
}

]


方法:

let list = test,
    data = []; 
    
for(var i = 0,length = test.length; i < length; i++) {
    if(!data[list[i].city]) {
        var arr = [];
        arr.push(list[i]);
        data[list[i].city] = arr;
    }else {
        data[list[i].city].push(list[i])
    }
}



你可能感兴趣的:(javaScript)