集团通过JavaScript属性对象(Group objects by property in ja

2019-08-20 10:11发布

如何转换这样的:

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

这个:

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

使用JavaScript或下划线

Answer 1:

假设原来的列表包含在一个名为变量list

_
.chain(list)
.groupBy('type')
.map(function(value, key) {
    return {
        type: key,
        foods: _.pluck(value, 'food')
    }
})
.value();


Answer 2:

不使用下划线:

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));

DEMO: http://jsfiddle.net/ErikE/nSLua/3/

幸得@ErikE为提高/降低我的原代码,以帮助冗余我不得不:)



Answer 3:

这里有一个稍微不同,但更宽泛的版本的@伊恩的回答

警告 :结果是从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



Answer 4:

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



Answer 5:

一个ES6解决这个老问题:

重复使用Array#reduce ,并收集按组项目到Map 。 使用蔓延到转换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); 



Answer 6:

您可以将对象的数组组通过与Alasql图书馆领域之一。 这个例子紧凑阵列完全按照你的例子:

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

尝试这个例子在的jsfiddle 。



Answer 7:

你也可以使用其他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');


文章来源: Group objects by property in javascript