Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
236 views
Welcome To Ask or Share your Answers For Others

1 Answer

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]]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...