group array of objects by id

后端 未结 8 544
抹茶落季
抹茶落季 2021-01-16 08:07

I am trying to loop through a array ob objects and group the items of the array into new arrays that have matching id:

API example:

    api_array [
          


        
8条回答
  •  终归单人心
    2021-01-16 08:18

    You could use the ids as properties of an object

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

提交回复
热议问题