求教!js二维数组中,如何把具有相同种类name的值筛选出来,组成三维数组
具体这样的,比如varcollege=[[{name:'北京'},{city:'西安'}],[{name:'上海'},{city:'包头'}],[{name:'广州'},...
具体这样的,比如var college = [[{name:'北京'}, {city:'西安'}],
[{name:'上海'},{city:'包头'}],
[{name:'广州'},{city:'福州'}],
[{name:'北京'},{city:'广州'}],
[{name:'广州'},{city:'太原'}],
[{name:'上海'},{city:'昆明'}]];
要得到这种:
[[
[{name:'北京'}, {city:'西安'}],
[{name:'北京'}, {city:'广州'}]
],
[
[{name:'上海'},{city:'包头'}],
[{name:'上海'},{city:'昆明'}]
],
[
[{name:'广州'},{city:'福州'}],
[{name:'广州'},{city:'太原'}]
]]; 展开
[{name:'上海'},{city:'包头'}],
[{name:'广州'},{city:'福州'}],
[{name:'北京'},{city:'广州'}],
[{name:'广州'},{city:'太原'}],
[{name:'上海'},{city:'昆明'}]];
要得到这种:
[[
[{name:'北京'}, {city:'西安'}],
[{name:'北京'}, {city:'广州'}]
],
[
[{name:'上海'},{city:'包头'}],
[{name:'上海'},{city:'昆明'}]
],
[
[{name:'广州'},{city:'福州'}],
[{name:'广州'},{city:'太原'}]
]]; 展开
1个回答
展开全部
var college = [
[{name:'北京'},{city:'西安'}],
[{name:'上海'},{city:'包头'}],
[{name:'广州'},{city:'福州'}],
[{name:'北京'},{city:'广州'}],
[{name:'广州'},{city:'太原'}],
[{name:'上海'},{city:'昆明'}]
];
var result = [];
for(var i = 0;i<college.length;i++){
var ci = college[i], obj = ci[0];
var isExisted = false;
for(var j =0;j<result.length;j++){
var rj = result[j];
if(rj.type==obj.name){
rj.push(ci);
isExisted = true;
break;
}
}
if(!isExisted){
var tmp = [ci];
tmp.type = obj.name;
result.push(tmp);
}
}
college = result;
console.log(college);
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询