Home > Software engineering >  How to make the function loop through the Array
How to make the function loop through the Array

Time:01-23

Having this Array of Objects:

let myFriends = [
  { title: "Osama", age: 39, available: true, skills: ["HTML", "CSS"] },
  { title: "Ahmed", age: 25, available: false, skills: ["Python", "Django"] },
  { title: "Sayed", age: 33, available: true, skills: ["PHP", "Laravel"] },
];

And this Variable: let chosen = 2;

I need to Destruct it depending on the chosen variable to get something like this:

// If chosen === 1

"Osama"
39
"Available"
"CSS"

// If chosen === 2

"Ahmed"
25
"Not Available"
"Django"

// If chosen === 3

"Sayed"
33
"Available"
"Laravel"

I Tried this code:

switch (chosen) {
  case 1:
    const { title: t1, age: a1, available: av1, skills: s1 } = myFriends[0];
    const [h1, c1] = myFriends[0].skills
    console.log(t1)
    console.log(a1)
    console.log(av1 ? "Available" : "Not Available")
    console.log(c1)
    break;
  case 2:
    const { title: t2, age: a2, available: av2, skills: s2 } = myFriends[1];
    const [h2, c2] = myFriends[1].skills
    console.log(t2)
    console.log(a2)
    console.log(av2 ? "Available" : "Not Available")
    console.log(c2)
    break;
  case 3:
    const { title: t3, age: a3, available: av3, skills: s3 } = myFriends[2];
    const [h3, c3] = myFriends[2].skills
    console.log(t3)
    console.log(a3)
    console.log(av3 ? "Available" : "Not Available")
    console.log(c3)
}

And it works, but I want to make a simpler code. So I tried this one:

function chosenPerson(chosen) {
  const { title: t, age: a, available: av, skills: s } = myFriends[`${chosen}`];
  const [h, c] = myFriends[`${chosen}`].skills
  console.log(t)
  console.log(a)
  console.log(av ? "Available" : "Not Available")
  console.log(c)
};

chosenPerson();

It didn't work, so how can i make the function change with the chosen variable

CodePudding user response:

Thanks to @Teemu the problem was that I didn't pass chosen to the function call. and there is no need to use this myFriends['${chosen}'].

all I needed were myFriends[chosen - 1] as the array is 0 based index, and to pass chosen to the function call like this chosenPerson(chosen)

CodePudding user response:

let myFriends = [
  { title: "Osama", age: 39, available: true, skills: ["HTML", "CSS"] },
  { title: "Ahmed", age: 25, available: false, skills: ["Python", "Django"] },
  { title: "Sayed", age: 33, available: true, skills: ["PHP", "Laravel"] },
];

let choosen = 2;
function getDetail(option){
  const {title, age, available, skills } = myFriends[option -1];
  
  return [title, age, available ? "Available" : "Non Available" , skills.join(',')]
}

console.log(getDetail(choosen));

Try this solution which return output inside an array I hope this will fix your problem.

  • Related