0

const persons = {
  p1: {
    first: "Yassine",
    last: "Boutabia",       
  },
  p2: {
    first: "Md Jahidul Hasan",
    last: "Mozumder",
  },
  p3: {
    first: "Md Feroj",
    last: "Ahmod",
  },
}

booYa = () => {
  var val = "first"; //just an idea came to me
  var arr = [];
  for (var key in persons) {
    if (persons.hasOwnProperty(key)) {
      arr.push(persons[key]);
    }
  }
  console.log(arr[0].val);
}

the variable arr represents the persons objects as array here. When i write console.log(arr[0].first); it outputs the first of p1 which is Yassine. So far so good. Now i am trying to do get this first from a variable. I want to put the first or last in a variable and chain it at the end of arr[0] so that i get that value. How can it be done?

ShocKwav3_
  • 1,670
  • 6
  • 22
  • 44

2 Answers2

0

Use []

console.log(arr[0][val]);
Sushanth --
  • 55,259
  • 9
  • 66
  • 105
0

You can use map to transform the array however you want and then display.

persons
  .map(p => `${p.name} ${p.last}`)
  .forEach(fullname => console.log(fullname))
Inanc Gumus
  • 25,195
  • 9
  • 85
  • 101