Home > Mobile >  Angular/Typescript - how to get a new list from objects depending on property?
Angular/Typescript - how to get a new list from objects depending on property?

Time:12-10

I have two lists of objects:

groups = [
  { 
    id: 1,
    ...
  },
  { 
    id: 2,
    ...
  },
  { 
    id: 3,
    ...
  }
]

devices = [
  { 
    id: 1,
    group_id: 1,
    ...
  },
  { 
    id: 2,
    group_id: 1,
    ...
  },
  { 
    id: 3,
    group_id: 2,
    ...
  }
]

Now I want to have a new list with grouped devices ids depending of a group_id.

groupedDevices = [
  {
    id: [1,2] //group 1
  },
  {
    id:[3] //group 2
  }
]

Or maybe in another form but it should be a new list. I tried looping after objects in both lists but no results, I can't get it

CodePudding user response:

  1. First group devices by group id:

    const devicesByGroupId = new Map<number, number[]>();
    for (const device of devices) {
      const devices = devicesByGroupId.get(device.group_id);
      if (!devices) {
        devicesByGroupId.set(device.group_id, [device.id]);
      } else {
        devices.push(device.id);
      }
    }
    
  2. Then, assign devices to the groups and filter out empty ones:

    let groupedDevices = groups.map(group => {
      return {
        id: devicesByGroupId.get(group.id) || []
      };
    })
    .filter(group => group.id.length > 0);
    

CodePudding user response:

<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>

Now first of all you need to group by list:

let devices = [
  { 
    id: 1,
    group_id: 1,
    ...
  },
  { 
    id: 2,
    group_id: 1,
    ...
  },
  { 
    id: 3,
    group_id: 2,
    ...
  }
]
let groupDevices=lodash.groupBy(devices,function(x){ return x.group_id });

Now make new list with grouped value:

let new=[];
lodash.forEach(groupDevices,function(x){
console.log(x);
new.push(lodash.map(x.id));
});
console.log(new);
  • Related