I am currently trying to extract the names, age and nation of each player inside the object. I used object keys and it was able to get the position name.
Note: This is vanilla Javascript
const arsenal = {
name: "Arsenal",
city: "London",
startingLineup: {
gk: { name: "Aaron Ramsdale", age: 24, country: "England" },
lb: { name: "Oleksandr Zinchenko", age: 26, country: "Ukraine" },
rb: { name: "Ben White", age: 25, country: "England" },
lcb: { name: "Gabriel Magalhaes", age: 25, country: "Brazil" },
rcb: { name: "William Saliba", age: 22, country: "France" },
cdm: { name: "Thomas Partey", age: 29, country: "Ghana" },
cm: { name: "Granit Xhaka", age: 30, country: "Switzerland" },
cam: { name: "Martin Odegaard", age: 23, country: "Norway" },
lw: { name: "Gabriel Martinelli", age: 21, country: "Brazil" },
rw: { name: "Bukayo Saka", age: 21, country: "England" },
st: { name: "Gabriel Jesus", age: 26, country: "Brazil" },
},
};
Object.keys(arsenal.startingLineup).forEach((pos) => {
const name = arsenal.startingLineup[pos.name];
console.log(pos, name);
});
But when I try to get the other information it comes out as undefined
. How can I get the rest of the player info?
gk undefined
lb undefined
rb undefined
lcb undefined
rcb undefined
cdm undefined
cm undefined
cam undefined
lw undefined
rw undefined
st undefined
5
Answers
There’s a small mistake. You’re using
pos.name
instead of justpos
.Change
[pos.name]
to[pos].name
:It’s simpler to iterate over
Object.entries
to have access to both the key and the value.To fix it you should use only pos as key and access name like this:
However, for convenience you can use Object.entries with destructure syntax:
this code is correct due to the fact that
pos
is not anobject
.To fix your code you can just change
[pos.name] to [pos].name
, the problem istypeof(pos) is String
, thus String.name gives you "undefined". I have listed the 4 new methods to loop anobject - arsenal.startingLineup{}
in anobject - arsenal{}