Gm *_*mmy 4 javascript arrays json destructuring ecmascript-6
我有一个来自“ https://randomuser.me/api/ ”的对象“数据” ,我在我的项目中使用了它。
{
"results": [
{
"gender": "female",
"name": {
"title": "miss",
"first": "mia",
"last": "sutton"
}
}
]
}
Run Code Online (Sandbox Code Playgroud)
我对数据对象的结果进行了如下解构;
const {results} = data;
我如何解构我创建的结果变量,并从中获取第一项我希望解构的数组项被声明为配置文件。这表示从我想在我的应用程序中显示的 API 调用中获取的用户个人资料数据。
你可以这样做:
const { results: [firstItem] } = data;
Run Code Online (Sandbox Code Playgroud)
有关解构的更多信息,请参阅此 MDN 文章。
const { results: [firstItem] } = data;
Run Code Online (Sandbox Code Playgroud)
根据您的代码(见评论),这也应该有效:
const data = {
"results": [
{
"gender": "female",
"name": {
"title": "miss",
"first": "mia",
"last": "sutton"
}
}
]
};
// declare a const variable named firstItem that holds the first element of the array
const { results: [firstItem] } = data;
// You could event destructure the content of this first array item like this
const { results: [{ gender, name }] } = data;
// or go deeper like this
const { results: [{ name: { title, first, last } }] } = data;
console.log(firstItem);
console.log(gender);
console.log(name);
console.log(title, first, last);Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7125 次 |
| 最近记录: |