Home > Software engineering >  Iterate over an object to see which active days matches per id
Iterate over an object to see which active days matches per id

Time:01-15

Consider the array of objects below,

const resource = [
    {
        id: 'tony',
        shiftday: [
            {active: '1', code: 'Sun'},
            {active: '1', code: 'Mon'},
            {active: '1', code: 'Tue'},
            {active: '1', code: 'Wed'},
            {active: '1', code: 'Thu'},
            {active: '1', code: 'Fri'},
            {active: '1', code: 'Sat'},
        ]
    },
    {
        id: 'alex',
        shiftday: [
            {active: '0', code: 'Sun'},
            {active: '1', code: 'Mon'},
            {active: '1', code: 'Tue'},
            {active: '0', code: 'Wed'},
            {active: '1', code: 'Thu'},
            {active: '1', code: 'Fri'},
            {active: '0', code: 'Sat'},
        ]
    },
    {
        id: 'trey',
        shiftday: [
            {active: '0', code: 'Sun'},
            {active: '1', code: 'Mon'},
            {active: '0', code: 'Tue'},
            {active: '1', code: 'Wed'},
            {active: '0', code: 'Thu'},
            {active: '1', code: 'Fri'},
            {active: '0', code: 'Sat'},
        ]
    },
]

I need to get all values that has active day set to 1 (selected) and match it to the other id's. And to be able to say that which id's have matching active days.

CodePudding user response:

Here is how you can achieve it. I just printed activeDays, instead, you can store it in a separate array, and reuse it after the loop.

const neededArrayOfIds = ['trey']; // <- Declare array of needed IDs

resource.forEach(elm => {
  if (neededArrayOfIds.includes(elm.id)) {
    const activeDays = elm.shiftday.filter(day => day.active == 1)
    console.log(activeDays)
  }
})

CodePudding user response:

It give active day array of object.

 const activeDays = resource.map(item => item.shiftday.filter(day => day.active === '1'));
 console.log(activeDay);

CodePudding user response:

Just use:

const filteredArr = resource.map((item) => {
 const filteredShiftDays = item.shiftday.filter((state) = state.active === '1');

 return {
  id: item.id,
  active: filteredShiftDays
 };
});

It returns all active days including the ID which days belongs to whom.

  •  Tags:  
  • Related