如何访问 JSON 响应中的嵌套值作为数组

How to access nested values in JSON response as an array

使用 const token = response.json().token; 我可以获得以下内容 JSON:

{
    "token": "*********",
    "roles": [
        {
            "id": 4,
            "name": "User",
            "pivot": {
                "user_id": 1,
                "role_id": 4
            }
        }
    ]
}

我希望能够以数组的形式访问角色中的名称。

如果您只想访问角色数组,假设您使用的是传统响应对象,您可以按照其他用户所述的方式访问它:

var roles = response.json().roles

当我重新阅读问题和评论时,我明白用户想要访问角色中的名称作为列表。假设是这样,地图函数会很好地做到这一点:

// Assuming we store response in "data"
var data = response.json();
var names = data.roles.map(function(role){return role.name});
console.log(names);
// Then "names" will look like ["User",...]

简而言之,map 将遍历调用它的数组和 运行 提供的函数,第一个参数是它在数组中看到的当前值。这个函数可以像上面那样动态定义,或者如果逻辑复杂或重复使用则预定义并传递。

这是 Map 及其兄弟 Reduce 的一种非常常见的用法。两者都经常用于将复杂的 variable-length 数据提炼成更简单的形式。

地图文档: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

更新: 原来的问题似乎是关于 ES6 的,所以这里是 "proper" 带有正确声明和箭头函数的 ES6 版本:

// Assuming we store response in "data"
const data = response.json();
const names = data.roles.map(role => role.name);
console.log(names);
// Then "names" will look like ["User",...]