32

如何转换这个:

[
    {food: 'apple', type: 'fruit'},
    {food: 'potato', type: 'vegetable'},
    {food: 'banana', type: 'fruit'},
]

进入这个:

[
    {type: 'fruit', foods: ['apple', 'banana']},
    {type: 'vegetable', foods: ['potato']}
]

使用 javascript 或下划线

4

7 回答 7

93

假设原始列表包含在名为 的变量中list

_
.chain(list)
.groupBy('type')
.map(function(value, key) {
    return {
        type: key,
        foods: _.pluck(value, 'food')
    }
})
.value();
于 2013-04-08T21:02:15.797 回答
17

不使用下划线:

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改进/减少我的原始代码以帮助我解决冗余:)

于 2013-04-08T20:16:35.453 回答
6

这是@Ian 答案的稍微不同但更通用的版本

警告:结果与 OP 要求略有不同,但像我这样偶然发现这个问题的其他人可能会受益于更通用的答案恕我直言

var origArr = [
   {food: 'apple', type: 'fruit'},
   {food: 'potato', type: 'vegetable'},
   {food: 'banana', type: 'fruit'}
];

function groupBy(arr, key) {
        var newArr = [],
            types = {},
            newItem, i, j, cur;
        for (i = 0, j = arr.length; i < j; i++) {
            cur = arr[i];
            if (!(cur[key] in types)) {
                types[cur[key]] = { type: cur[key], data: [] };
                newArr.push(types[cur[key]]);
            }
            types[cur[key]].data.push(cur);
        }
        return newArr;
}

console.log(groupBy(origArr, 'type'));

你可以在这里找到一个 jsfiddle

于 2015-11-23T17:08:59.033 回答
4

这个老问题的 ES6 解决方案:

迭代 using Array#reduce,并按组将项目收集到Map. 使用 spread 将Map#values后面转换为数组:

const data = [
    {food: 'apple', type: 'fruit'},
    {food: 'potato', type: 'vegetable'},
    {food: 'banana', type: 'fruit'},
];

const result = [...data.reduce((hash, { food, type }) => {
  const current = hash.get(type) || { type, foods: [] };
  
  current.foods.push({ food });
  
  return hash.set(type, current);
}, new Map).values()];

console.log(result);

于 2016-12-11T15:04:51.517 回答
2
var foods = [
    {food: 'apple', type: 'fruit'},
    {food: 'potato', type: 'vegetable'},
    {food: 'banana', type: 'fruit'}
];

var newFoods = _.chain( foods ).reduce(function( memo, food ) {
  memo[ food.type ] = memo[ food.type ] || [];
  memo[ food.type ].push( food.food );
  return memo;
}, {}).map(function( foods, type ) {
    return {
        type: type,
        foods: foods
    };
}).value();

http://jsbin.com/etaxih/2/edit

于 2013-04-08T20:19:02.887 回答
0

您可以使用 Alasql 库按字段之一对对象数组进行分组。此示例紧凑数组与您的示例完全相同:

var res = alasql('SELECT type, ARRAY(food) AS foods FROM ? GROUP BY type',[food]);

在 jsFiddle试试这个例子。

于 2014-12-22T02:07:13.530 回答
0

您还可以使用其他 ES6 功能,例如:

function groupArray(arr, groupBy, keepProperty) {
        let rArr = [], i;
        arr.forEach(item => {
            if((i = rArr.findIndex(obj => obj[groupBy] === item[groupBy])) !== -1)
                rArr[i][`${keepProperty}s`].push(item[keepProperty]);
            else rArr.push({
                [groupBy]: item[groupBy],
                [`${keepProperty}s`]: [item[keepProperty]]
            });
        });
        return rArr;
    }

    groupArray(yourArray, 'type', 'food');
于 2017-01-27T07:39:19.843 回答