我在项目中使用了一个来自“ https://randomuser.me/api/”的对象“数据”。
{
"results": [
{
"gender": "female",
"name": {
"title": "miss",
"first": "mia",
"last": "sutton"
}
}
]
}
我从数据对象中解构了结果,如下所示;
const {results} = data;
如何解构我创建的结果变量,并从中获取第一项,我希望将解构后的数组项声明为配置文件。这代表我想在我的应用程序中显示的API调用中获得的用户个人资料数据。
答案 0 :(得分:1)
您可以这样做:
INT(10) UNSIGNED
有关解构的更多信息,请参见this MDN article。
const { results: [firstItem] } = data;
根据您的代码(请参阅注释),这也应该起作用:
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);