Home > Net >  How can I access the prop of the objects in an array with function, for loop and a conditional state
How can I access the prop of the objects in an array with function, for loop and a conditional state

Time:04-22

I'd love to know how I can access the property of objects nested in an array through the use of function, for loop, and a conditional statement.

const details = [
  {
    first: "Liverpool",
    second: 'Man City',
    third: 'Chelsea',
    fourth: 'Tottenham',
    similarity: 'EPL'
  },
    {
    first: "Real Madrid",
    second: 'Barcelona',
    third: 'Villareal',
    fourth: 'Sevilla',
    similarity: 'La Liga'
  }
]



function team(name,prop){
  for (let i = 0; i < details.length; i  ){
    if(details[i].first === name && details[i].name[prop] === prop){
      return true;
    } else {
      return false;
    }
  }
}

console.log(team('Liverpool','EPL'));

This isn't the main code but this should work. I'm trying to check if the second argument which is passed in the function call is a property of one of the objects. If it is one of it, it should return true if it isn't, it should return false. To me, the main problem is on the 22nd line: ....details[i].name[prop] === prop)

I don't really know how to make that work. Please, help.

CodePudding user response:

If the idea is to always compare with similarity, the method would be:

function team(name,prop){
  for (let i = 0; i < details.length; i  ){
    if(details[i].first === name && details[i].similarity === prop){
      return true;
    } else {
      return false;
    }
  }
}
team('Liverpool', 'EPL')

But if the property can be dynamic it would be:

function team(name, prop, cup){
  for (let i = 0; i < details.length; i  ){
    if(details[i].first === name && details[i][prop] === cup){
      return true;
    } else {
      return false;
    }
  }
}
team('Liverpool', 'similarity', 'EPL')

Another alternative is if you want to go through all the names, then it can be like this:

function team(name,prop){
  for (let i = 0; i < details.length; i  ){
    const teams = Object.entries(details[i])
    const similarity = details[i].similarity;

    for (let j = 0; j < teams.length; j  ){
      if (teams[j][1] === name && similarity === prop){
        return true;
      }
    }

  }
  return false;
}
team('Man City', 'EPL')

Hope this helps.

  • Related