对targetArray
进行分类并看起来像desiredArray
的最简单方法是什么?
var targetArray = ["volvo|car", "bmw|car", "suzuki|mc"];
var desiredArray = {
"car" : {
"volvo",
"bmw",
"audi"
},
"mc" : {
"suzuki"
}
};
答案 0 :(得分:3)
var result = {}
$.each(["volvo|car", "bmw|car", "suzuki|mc"], function(index, item){
// split at pipe
var split = item.split('|');
// create array for car type if there is not already one
if(!result[split[1]])result[split[1]] = [];
// push to that array
result[split[1]].push(split[0]);
});