Home > Software engineering >  Loop over array of Ids and add hours based on ID
Loop over array of Ids and add hours based on ID

Time:08-16

Data:

[
  { idMembers: [ '62d7001a7446ee76e5e2856f' ], hours: 5 },
  {
    idMembers: [ '62d6f80e28907a0385a3a41e', '62d7001a7446ee76e5e2856f' ],
    hours: 4
  }
]

I need to take each unique id in the idMembers array and add up hours in all objects for that id. So id '62d7001a7446ee76e5e2856f' will have 9 hours after loop and id '62d7001a7446ee76e5e2856f' will have 4.

Additional info: The data will be longer with more ids and hours added to this overall array. I would like the end result to look like [{'62d7001a7446ee76e5e2856f':9},{'62d6f80e28907a0385a3a41e':4}] but I have no clue on how to obtain this. (So adding up the hours and linking them to that id)

CodePudding user response:

Something like this would do the job. You have to iterate over every idMember and store in an object (or map) the key/value pair of the hours for each member, adding to the previous value the new hours.

let obj = {};
data.forEach(item => {
    for (let memberId of item.idMembers) {
        let oldHours = obj[memberId] ? obj[memberId] : 0;
        obj[memberId] = oldHours   item.hours;
    }
});

CodePudding user response:

Iterate each object in your data, then iterate the array idMembers.

Store each member in another object, check if the id exists, if so increment the value (hours), else set the initial value.

const data = [
  { idMembers: [ '62d7001a7446ee76e5e2856f' ], hours: 5 },
  {
    idMembers: [ '62d6f80e28907a0385a3a41e', '62d7001a7446ee76e5e2856f' ],
    hours: 4
  }
]

const members = {}

data.forEach( row => {

  for (let member of row.idMembers) {
    if (typeof members[member] !== 'undefined') {
      members[member]  = row.hours
    } else {
      members[member] = row.hours
    }
  }
  
})

console.log(members)

  • Related