我有一个数组:
["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或Underscore中执行此操作?
最佳答案
因此,假设这样的数组:
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"]
}