不使用下划线:
var origArr = [
{food: 'apple', type: 'fruit'},
{food: 'potato', type: 'vegetable'},
{food: 'banana', type: 'fruit'}
];
/*[
{type: 'fruit', foods: ['apple', 'banana']},
{type: 'vegetable', foods: ['potato']}
]*/
function transformArr(orig) {
var newArr = [],
types = {},
i, j, cur;
for (i = 0, j = orig.length; i < j; i++) {
cur = orig[i];
if (!(cur.type in types)) {
types[cur.type] = {type: cur.type, foods: []};
newArr.push(types[cur.type]);
}
types[cur.type].foods.push(cur.food);
}
return newArr;
}
console.log(transformArr(origArr));
演示:http: //jsfiddle.net/ErikE/nSLua/3/
感谢@ErikE改进/减少我的原始代码以帮助我解决冗余:)