按ID将对象分组

时间:2019-10-17 13:33:43

标签: javascript

我正在尝试遍历对象的数组并将数组中的项分组为具有匹配ID的新数组:

API示例:

    api_array [
       {id: 1, postcode: 'xxx', street: 'xxx', city: 'xxx'},
       {id: 1, postcode: 'xxx', street: 'xxx', city: 'xxx'},
       {id: 1, postcode: 'xxx', street: 'xxx', city: 'xxx'},
       {id: 2, postcode: 'xxx', street: 'xxx', city: 'xxx'},
       {id: 2, postcode: 'xxx', street: 'xxx', city: 'xxx'},
       {id: 2, postcode: 'xxx', street: 'xxx', city: 'xxx'},
       {id: 3, postcode: 'xxx', street: 'xxx', city: 'xxx'},
       {id: 3, postcode: 'xxx', street: 'xxx', city: 'xxx'},
       {id: 3, postcode: 'xxx', street: 'xxx', city: 'xxx'},
       {id: 4, postcode: 'xxx', street: 'xxx', city: 'xxx'},
       {id: 4, postcode: 'xxx', street: 'xxx', city: 'xxx'},
       {id: 4, postcode: 'xxx', street: 'xxx', city: 'xxx'},
   ];

我正在努力达到这个结果:

result [
group_one [
       {id: 1, postcode: 'xxx', street: 'xxx', city: 'xxx'},
       {id: 1, postcode: 'xxx', street: 'xxx', city: 'xxx'},
       {id: 1, postcode: 'xxx', street: 'xxx', city: 'xxx'},
]
group_two [
       {id: 2, postcode: 'xxx', street: 'xxx', city: 'xxx'},
       {id: 2, postcode: 'xxx', street: 'xxx', city: 'xxx'},
       {id: 2, postcode: 'xxx', street: 'xxx', city: 'xxx'},
]
group_three [
       {id: 3, postcode: 'xxx', street: 'xxx', city: 'xxx'},
       {id: 3, postcode: 'xxx', street: 'xxx', city: 'xxx'},
       {id: 3, postcode: 'xxx', street: 'xxx', city: 'xxx'},
]
group_four [
       {id: 4, postcode: 'xxx', street: 'xxx', city: 'xxx'},
       {id: 4, postcode: 'xxx', street: 'xxx', city: 'xxx'},
       {id: 4, postcode: 'xxx', street: 'xxx', city: 'xxx'},
]
]

我实际上已经设法实现了它,但是我认为它是疯狂的,并且确信这里有一个更好的实现是我所做的:

const createAddresses = (address) => {


        let group_one= [],
        group_two = [],
        group_three = [],
        group_four = [],
          group = [];

        debugger;
        for(let i=0; i < address.length; i++) {             
            switch (address[i].id) {
                case 1:
                        group_one.push(address[i]);
                    break;
                case 2:
                        group_two.push(address[i]);
                    break;
                case 3:
                        group_three.push(address[i]);
                    break;
                case 4:
                        group_four.push(address[i]);
                    break;
                default:
                    return address;                
            }
        }



        console.log('GROUP', group);
        return group.push(group_one, group_two, group_three, group_four);
    }

我真的不喜欢这种实现方式,并且已经尝试过:

const obj = address.reduce((acc, cur) => ({...acc, [cur.id]: cur}), {});

上面的操作与我疯狂的for循环功能相同,但是它只为每个组添加最后一个元素,如下所示:

result [
    0 [
           {id: 1, postcode: 'xxx', street: 'xxx', city: 'xxx'},
    ]
    1 [
           {id: 2, postcode: 'xxx', street: 'xxx', city: 'xxx'},
    ]
    2 [
           {id: 3, postcode: 'xxx', street: 'xxx', city: 'xxx'},
    ]
    3 [`enter code here`
           {id: 4, postcode: 'xxx', street: 'xxx', city: 'xxx'},
    ]
    ]

但是就像我提到的那样,我需要每组旁的所有元素任何建议。

8 个答案:

答案 0 :(得分:2)

按ID组对象数组

//Create a javascript array of objects containing key value pairs id, post 
var api_array = [ 
       {id: 1, postcode: '10'}, 
       {id: 1, postcode: '11'}, 
       {id: 2, postcode: '20'}, 
       {id: 2, postcode: '21'}, 
       {id: 2, postcode: '22'}, 
       {id: 3, postcode: '30'} 
   ];  
//result is a javascript array containing the groups grouped by id. 
let result = []; 

//javascript array has a method foreach that enumerates keyvalue pairs. 
api_array.forEach(  
    r => { 
        //if an array index by the value of id is not found, instantiate it. 
        if( !result[r.id] ){  
            //result gets a new index of the value at id. 
            result[r.id] = []; 
        } 
        //push that whole object from api_array into that list 
        result[r.id].push(r); 
    }   
); 
console.log(result[1]); 
console.log(result[2]); 
console.log(result[3]);

打印:

[ { id: 1, postcode: '10' }, { id: 1, postcode: '11' } ]

[ { id: 2, postcode: '20' }, 
  { id: 2, postcode: '21' },
  { id: 2, postcode: '22' } ]

[ { id: 3, postcode: '30' } ]

答案 1 :(得分:1)

https://jsfiddle.net/u4k16ojz/5/

var result = new Array(4);
api_array.forEach(function(item, index){
  if (!result[item.id]){
    result[item.id] = [];
  }
  result[item.id].push(item);
})

答案 2 :(得分:0)

您可以使用Map对相同的id进行分组,然后从地图中获取值作为结果集。

结果集与所需键的顺序相同。

function groupBy(array, key) {
    return Array.from(array
        .reduce((m, o) => m.set(o[key], [...(m.get(o[key]) || []), o]), new Map)
        .values()
    );
}

var data = [{ id: 1, postcode: 'xxx', street: 'xxx', city: 'xxx' }, { id: 1, postcode: 'xxx', street: 'xxx', city: 'xxx' }, { id: 1, postcode: 'xxx', street: 'xxx', city: 'xxx' }, { id: 2, postcode: 'xxx', street: 'xxx', city: 'xxx' }, { id: 2, postcode: 'xxx', street: 'xxx', city: 'xxx' }, { id: 2, postcode: 'xxx', street: 'xxx', city: 'xxx' }, { id: 3, postcode: 'xxx', street: 'xxx', city: 'xxx' }, { id: 3, postcode: 'xxx', street: 'xxx', city: 'xxx' }, { id: 3, postcode: 'xxx', street: 'xxx', city: 'xxx' }, { id: 4, postcode: 'xxx', street: 'xxx', city: 'xxx' }, { id: 4, postcode: 'xxx', street: 'xxx', city: 'xxx' }, { id: 4, postcode: 'xxx', street: 'xxx', city: 'xxx' }],
    grouped = groupBy(data, 'id');

console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 3 :(得分:0)

类似于您的reduce示例,此操作遍历数据并使用对象ID作为键并将它们分组在一起来创建对象。然后,它从该对象获取值。

const api_array = [{id: 1, postcode: 'xxx', street: 'xxx', city: 'xxx'},{id: 1, postcode: 'xxx', street: 'xxx', city: 'xxx'},{id: 1, postcode: 'xxx', street: 'xxx', city: 'xxx'},{id: 2, postcode: 'xxx', street: 'xxx', city: 'xxx'},{id: 2, postcode: 'xxx', street: 'xxx', city: 'xxx'},{id: 2, postcode: 'xxx', street: 'xxx', city: 'xxx'},{id: 3, postcode: 'xxx', street: 'xxx', city: 'xxx'},{id: 3, postcode: 'xxx', street: 'xxx', city: 'xxx'},{id: 3, postcode: 'xxx', street: 'xxx', city: 'xxx'},{id: 4, postcode: 'xxx', street: 'xxx', city: 'xxx'},{id: 4, postcode: 'xxx', street: 'xxx', city: 'xxx'},{id: 4, postcode: 'xxx', street: 'xxx', city: 'xxx'}];

const out = Object.values(api_array.reduce((acc, c) => {
  const { id } = c;

  // If the object doesn't have a key that matches the id
  // create an array as its value and then concat the current object
  // to it, otherwise, if the key exists just concat the current object
  // to the existing array
  acc[id] = (acc[id] || []).concat(c);
  return acc;
}, {}));

console.log(out)

答案 4 :(得分:0)

16:32:00

答案 5 :(得分:0)

尝试这样实现:

group_1

注意:结果将包含键group_2group_one ...而不是group_twoextend ...

如果严格需要,请为键和值创建一个数组,将1转换为1。

答案 6 :(得分:0)

您可以将id用作对象的属性

let api_array = [
    {id: 1, postcode: 'xxx', street: 'xxx', city: 'xxx'},
    {id: 1, postcode: 'xxx', street: 'xxx', city: 'xxx'},
    {id: 1, postcode: 'xxx', street: 'xxx', city: 'xxx'},
    {id: 2, postcode: 'xxx', street: 'xxx', city: 'xxx'},
    {id: 2, postcode: 'xxx', street: 'xxx', city: 'xxx'},
    {id: 2, postcode: 'xxx', street: 'xxx', city: 'xxx'},
    {id: 3, postcode: 'xxx', street: 'xxx', city: 'xxx'},
    {id: 3, postcode: 'xxx', street: 'xxx', city: 'xxx'},
    {id: 3, postcode: 'xxx', street: 'xxx', city: 'xxx'},
    {id: 4, postcode: 'xxx', street: 'xxx', city: 'xxx'},
    {id: 4, postcode: 'xxx', street: 'xxx', city: 'xxx'},
    {id: 4, postcode: 'xxx', street: 'xxx', city: 'xxx'},
];

let grouped = groupArray(api_array);

console.log(grouped);
console.log(grouped[1]);

function groupArray(myArray) {
    let grouped = {};

    for (let i = 0; i < myArray.length; i++) {
        let row = myArray[i];
        let group = grouped[row.id];
        if (!group) {
            group = [];
            grouped[row.id] = group;
        }
        group.push(row);
    }

    return grouped;
}

答案 7 :(得分:-1)

api_array [
       {id: 1, postcode: 'xxx', street: 'xxx', city: 'xxx'},
       {id: 1, postcode: 'xxx', street: 'xxx', city: 'xxx'},
       {id: 1, postcode: 'xxx', street: 'xxx', city: 'xxx'},
       {id: 2, postcode: 'xxx', street: 'xxx', city: 'xxx'},
       {id: 2, postcode: 'xxx', street: 'xxx', city: 'xxx'},
       {id: 2, postcode: 'xxx', street: 'xxx', city: 'xxx'},
       {id: 3, postcode: 'xxx', street: 'xxx', city: 'xxx'},
       {id: 3, postcode: 'xxx', street: 'xxx', city: 'xxx'},
       {id: 3, postcode: 'xxx', street: 'xxx', city: 'xxx'},
       {id: 4, postcode: 'xxx', street: 'xxx', city: 'xxx'},
       {id: 4, postcode: 'xxx', street: 'xxx', city: 'xxx'},
       {id: 4, postcode: 'xxx', street: 'xxx', city: 'xxx'},
];

let result = [];
for (let i = 0; i < numberOfGroupsIWantToMake; i++) {
    let newGroupArray = api_array.filter(obj => obj.id === i);
    result.push(newGroupArray);
}

return result;

注意:这是 A 解决方案,但性能不如我们遍历整个数组n次。