group array of objects by id

后端 未结 8 543
抹茶落季
抹茶落季 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:16

    group array of objects by 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]);
    

    Prints:

    [ { id: 1, postcode: '10' }, { id: 1, postcode: '11' } ]
    
    [ { id: 2, postcode: '20' }, 
      { id: 2, postcode: '21' },
      { id: 2, postcode: '22' } ]
    
    [ { id: 3, postcode: '30' } ]
    

提交回复
热议问题