0

I am trying to access a property’s value in an object, I know the name of the properties, but not the name of the object (if that makes sense). This object name is retrieved from an array. Sorry I’m not very good with explaining things, but hopefully an example will help… So for example…

const names = ["john", "ben", "doe"]

const john = {
  age: 33,
  hobby: "coding"
};

const ben = {
  age: 25,
  hobby: "soccer"
};

const doe = {
  age: 20,
  hobby: "playing games"
};

names.forEach((name) => {
  console.log(name.age)
  console.log(name.hobby)
});

So as you can see, I know what properties each object has, the object name I also know, but it is being passed in an array of strings. When I run this code, it will log undefined, how would I be able to retrieve the age and hobby of each of the values in the array?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Hans
  • 3
  • 3
  • Objects don't have names. What you've got are variables whose values happen to be objects, but the names of the variables have nothing to do with the objects involved. You're going about this the wrong way: put your objects in an array or in another object as property values. – Pointy May 20 '22 at 23:08
  • `john`, `ben` and `doe` are not properties in an object – Bergi May 20 '22 at 23:17

0 Answers0