Javascript中的分解和嵌套数组

时间:2014-02-24 16:38:41

标签: javascript jquery arrays object

targetArray进行分类并看起来像desiredArray的最简单方法是什么?

var targetArray = ["volvo|car", "bmw|car", "suzuki|mc"];

var desiredArray = {
    "car" : {
        "volvo",
        "bmw",
        "audi"
    },
    "mc" : {
        "suzuki"
    }
};

1 个答案:

答案 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]);
});