Using const token = response.json().token;
I am able to get the following JSON:
{
"token": "*********",
"roles": [
{
"id": 4,
"name": "User",
"pivot": {
"user_id": 1,
"role_id": 4
}
}
]
}
I want to be able to access the names within the roles as an array.
If you just want to access the array of roles, assuming you're using a traditional response object, you can just access it the way other users have stated:
var roles = response.json().roles
As I reread the question and comments, I get the idea that the user wants to access the names within the roles as as list. Assuming so, the map function will do this nicely:
// 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",...]
In a nutshell, map will walk the array it's called against and run the provided function against it, with the first argument being the current value it sees in the array. This function can be defined on the fly as above, or predefined and passed if the logic is complex or reused.
This is a very common use for Map, and its sibling, Reduce. Both are often used for distilling complex, variable-length data down to a simpler form.
Map documentiation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Update: It would appear the original question was asked regarding ES6, so here's the "proper" ES6 version with proper declarations and arrow funcs:
// 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",...]
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments