简体   繁体   English

在 Javascript 中解构 json 对象

[英]Destructuring a json object in Javascript

How would access the _id and state values?如何访问 _id 和 state 值?

Here's the data这是data

{
    "data": {
        "totalSamplesTested": "578841",
        "totalConfirmedCases": 61307,
        "totalActiveCases": 3627,
        "discharged": 56557,
        "death": 1123,
        "states": [
            {
                "state": "Lagos",
                "_id": "O3F8Nr2qg",
                "confirmedCases": 20555,
                "casesOnAdmission": 934,
                "discharged": 19414,
                "death": 207
            },
            {
                "state": "FCT",
                "_id": "QFlGp4md3y",
                "confirmedCases": 5910,
                "casesOnAdmission": 542,
                "discharged": 5289,
                "death": 79
            }
        ]
    }
}

What you have shown is a string in JSON format.您显示的是 JSON 格式的字符串。 You can convert that to a JavaScript object and then start to get the values you need from it.您可以将其转换为 JavaScript 对象,然后开始从中获取所需的值。

let str = ‘{
    "data": {
        "totalSamplesTested": "578841",
        "totalConfirmedCases": 61307,
        "totalActiveCases": 3627,
        "discharged": 56557,
        "death": 1123,
        "states": [
            {
                "state": "Lagos",
                "_id": "O3F8Nr2qg",
                "confirmedCases": 20555,
                "casesOnAdmission": 934,
                "discharged": 19414,
                "death": 207
            },
            {
                "state": "FCT",
                "_id": "QFlGp4md3y",
                "confirmedCases": 5910,
                "casesOnAdmission": 542,
                "discharged": 5289,
                "death": 79
            }
        ]
    }
} ‘;

(Note, I have put the string in single quotes so it can be shown properly here but in your code you need to put it in back ticks so it can span many lines) (注意,我已将字符串放在单引号中,因此可以在此处正确显示,但在您的代码中,您需要将其放在后面的勾号中,以便它可以跨越多行)

Now convert it to a JavaScript object.现在将其转换为 JavaScript 对象。

let obj = JSON.parse(str);让 obj = JSON.parse(str);

Now look closely at the string to see how the object is structured.现在仔细查看字符串以了解对象的结构。 It actually has just one item in it, data.它实际上只有一项,数据。 And that is itself an object with several items, one of which is states which is an array.这本身就是一个包含多个项目的对象,其中之一是状态,它是一个数组。

So, obj.data.states[0] is the array's first entry.因此, obj.data.states[0] 是数组的第一个条目。 That is an object and has _id and state items.那是一个对象,具有 _id 和状态项。

You can step through the array extracting the ._id and .state entries.您可以单步执行提取 ._id 和 .state 条目的数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM