Javascript将数组按值转换为分组对象

时间:2014-10-24 14:00:24

标签: javascript arrays underscore.js

我有一个数组:

["car1-coupe", "car2-convertible", "car2-hatchback", "car2-estate", "car3-hatchback", "car3-estate"] 

阵列可以有不同的汽车组,我想把它变成这样的东西:

[{
    car1: ["car1-coupe"]
},{
    car2: ["car2-convertible", "car2-hatchback", "car2-estate"]
},{
    car3: ["car3-hatchback", "car3-estate"]
}]

我如何在JavaScript或下划线中执行此操作?

3 个答案:

答案 0 :(得分:2)

所以,假设一个这样的数组:

var a = ["car1-coupe", "car2-convertible", "car2-hatchback", "car2-estate", "car3-hatchback", "car3-estate"];

你可以这样做:

var b = a.reduce(function(prev, curr){
    var car = curr.split('-')[0]; // "get" the current car
    prev[car] = prev[car] || [];  // Initialize the array for the current car, if necessary.
    prev[car].push(curr);         // Add the current item to the array.
    return prev;
}, {});

这将返回以下对象:

{
    car1: ["car1-coupe"],
    car2: ["car2-convertible", "car2-hatchback", "car2-estate"],
    car3: ["car3-hatchback", "car3-estate"]
}

答案 1 :(得分:0)



var array = ["car1-coupe", "car2-convertible", "car2-hatchback", "car2-estate", "car3-hatchback", "car3-estate"];

var result = {};

for (var i = 0; i < array.length; i++) {
  var key = array[i].split('-')[0]; // The car we're interested in
  if (result[key]) { // Check if this car has already been initialized
    result[key].push(array[i]); //add this model to the list
  } else {
    result[key] = [array[i]]; // initialize the array with the first value
  }
}

console.log(result);
/*will return :
{
  car1: ["car1-coupe"],
  car2: ["car2-convertible", "car2-hatchback", "car2-estate"],
  car3: ["car3-hatchback", "car3-estate"]
}
*/
&#13;
&#13;
&#13;

答案 2 :(得分:-1)

var  myObj = {}, myArr = [];
for( var i = 0; i < arr.length; i+=1) {
      var key = arr[i].split("-")[0];
      myObj = {};
      myObj[key] = [];
      for( var j = i; j < arr.length; j+=1 ) {
            if( key === arr[j].split("-")[0])
                myObj[key].push(arr[j]);
      }
      myArr.push(myObj);
}

我认为这可以通过这种方式简单地完成。一个循环获取密钥,另一个内循环获取此密钥的所有值。