如何获取下一个 JSON 项

How To Get Next JSON Item

本文关键字:下一个 JSON 获取 何获取      更新时间:2023-09-26

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

此外,我相信有一个专有术语将数据从一种类型转换为另一种类型。任何人都有可能知道它是什么...它就在我舌尖上!

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

在 JavaScript 中,Object 属性的顺序无法保证(ECMAScript Third Edition (pdf):)

4.3.3 对象 对象是对象类型的成员。它是属性的无序集合,每个属性都包含一个基元 值、对象或函数。存储在 对象称为方法。

如果订单不必

保证,您可以执行以下操作:

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

如果顺序很重要,我建议使用另一个数组来保存名称的顺序["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];