Home > Back-end >  loopin throug object and array using hasOwnProperty
loopin throug object and array using hasOwnProperty

Time:10-30

i have this object:

obj = {23-10-2022: 3, 24-10-2022: 1, 28-10-2022: 4, 29-10-2022: 1, 30-10-2022: 1}

and this dates array:

dates = [19-10-2022, 20-10-2022, 21-10-2022, 22-10-2022, 23-10-2022, 24-10-2022, 25-10-2022, 26-10-2022, 27-10-2022, 28-10-2022, 29-10-2022, 30-10-2022, 31-10-2022]

i want to loop throug the obj and array and to check: if the first key in the obj === dates[i] so return obj[key]=(the value) and move to the next obj key but continue from the next dates[i] and not from the begginnig elese return the 0.

at the end i want to get in return: 0,0,0,0,3,1,0,0,0,4,1,1

here is my code:

  for (let key in obj){
    for (let i = 0; i < dates.length; i  ){
      if (obj.hasOwnProperty(key)) {
        let value = obj[key];
        let date = dates[i];
        return key
        if(key===date){
          return value;
          key   ///gives NaN not correct
        }
        else{
          return 0; 
        }  
      }
    }
  }

what i need to change?

at the moment it return: [0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4] becuse it gets back to the firt dates value and re-check.

CodePudding user response:

You can just map() over the dates array. Here using the nullish coalescing operator (??) to assign 0 if retrieving the property returns undefined.

const obj = { '23-10-2022': 3, '24-10-2022': 1, '28-10-2022': 4, '29-10-2022': 1, '30-10-2022': 1 }
const dates = ['19-10-2022', '20-10-2022', '21-10-2022', '22-10-2022', '23-10-2022', '24-10-2022', '25-10-2022', '26-10-2022', '27-10-2022', '28-10-2022', '29-10-2022', '30-10-2022', '31-10-2022']

const result = dates.map(date => obj[date] ?? 0);

console.log(result)

  • Related