如何获取下一个JSON项目

Jon*_*Jon 1 javascript json

我想知道如果我有JavaScript的密钥,我将如何获得下一个JSON项目.例如,如果我提供关键'Josh',我如何获得'Annie'的内容以及'Annie'这个词?我是否必须在数组中处理JSON并从那里提取?

此外,我认为有一个适当的术语可以将数据从一种类型转换为另一种类型.任何人都知道它是什么......这只是我的舌尖!

{
    "friends": {
        "Charlie": {
            "gender": "female",
            "age": "28"
        },
        "Josh": {
            "gender": "male",
            "age": "22"
        },
        "Annie": {
            "gender": "female",
            "age": "24"
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*172 8

在JavaScript对象属性的顺序,不能保证(ECMAScript的第三版(PDF): )

4.3.3对象对象是Object类型的成员.它是一个无序的属性集合,每个属性都包含一个原始值,对象或函数.存储在对象属性中的函数称为方法.

如果不必保证订单,您可以执行以下操作:

var t = {
    "friends": {
        "Charlie": {
            "gender": "female",
            "age": "28"
        },
        "Josh": {
            "gender": "male",
            "age": "22"
        },
        "Annie": {
            "gender": "female",
            "age": "24"
        }
    }
};

// Get all the keys in the object
var keys = Object.keys(t.friends);

// Get the index of the key Josh
var index = keys.indexOf("Josh");

// Get the details of the next person
var nextPersonName = keys[index+1];
var nextPerson = t.friends[nextPersonName];
Run Code Online (Sandbox Code Playgroud)

如果订单很重要,我建议使用另一个数组来保存名称的顺序["Charlie", "Josh", "Annie"]而不是使用Object.keys().

var t = ...;

// Hard code value of keys to make sure the order says the same
var keys = ["Charlie", "Josh", "Annie"];

// Get the index of the key Josh
var index = keys.indexOf("Josh");

// Get the details of the next person
var nextPersonName = keys[index+1];
var nextPerson = t.friends[nextPersonName];
Run Code Online (Sandbox Code Playgroud)