问题
Suppose I have several nested objects(human1, human2, human3) in "human" object.
human: {
"human1": {
"name" : "John",
"sex" : "male",
"age" : 18
}
"human2": {
"name" : "Peter",
"sex" : "male",
"age" : 16
}
"human3": {
"name" : "May",
"sex" : "female",
"age" : 19
}
}
And I have another object called currentPlayer below, which I want it to be a vessel, in order to access the data from "human1", "human2", or "human3" for different use.
currentPlayer: {
"name" : "default",
"sex" : "default",
"age" : 0
}
Example: today I want currentPlayer to be John, and it goes
currentPlayer: {
"name" : "John",
"sex" : "male",
"age" : 18
}
And then I want currentPlayer to be Peter, and it goes:
currentPlayer: {
"name" : "Peter",
"sex" : "male",
"age" : 16
}
How do I iterate property values of currentPlayer like this with loop, not just key in one by one? Thanks...
回答1:
Bellow code will iterate through all Properties of human object
listofhuman = Object.getOwnPropertyNames(human);
var currentPlayer;
for (var objHumanName in listofhuman) {
if (listofhuman[objHumanName].Name === "Jonh") {
currentPlayer = Object.create(listofhuman[objHumanName]);
break;
}
}
at the end of this loop you will get human which you wonted
if you do Object.getOwnPropertyNames(currentPlayer)
this will return array of string which are the actual keys in object currentPlayer, and you can access those values by currentPlayer[arryofProp[0]]
来源:https://stackoverflow.com/questions/36846682/iterate-object-with-loop-between-different-data-options