本文介绍了使用不同数据选项之间的循环迭代对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在人类对象中有几个嵌套对象(human1,human2,human3)。

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

我在下面有另一个名为 currentPlayer 的对象,我希望它是一个容器,以便从human1,human2访问数据,或human3用于不同用途。

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
}

示例:今天我希望currentPlayer成为John,它就是

Example: today I want currentPlayer to be John, and it goes

currentPlayer: {
    "name" : "John",
    "sex" : "male",
    "age" : 18
}

然后我希望currentPlayer成为Peter,它就是:

And then I want currentPlayer to be Peter, and it goes:

currentPlayer: {
    "name" : "Peter",
    "sex" : "male",
    "age" : 16
}

如何使用循环迭代currentPlayer的属性值,而不仅仅是逐个键入?谢谢...

How do I iterate property values of currentPlayer like this with loop, not just key in one by one? Thanks...

推荐答案

Bellow代码将遍历人类对象的所有属性

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

如果你做 Object.getOwnPropertyNames(currentPlayer)这将返回字符串数组,这是实际的键在对象currentPlayer中,您可以通过 currentPlayer [arryofProp [0]]

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

这篇关于使用不同数据选项之间的循环迭代对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 01:03