不使用下划线:
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为提高/降低我的原代码,以帮助冗余我不得不:)