如何在Javascript中构造一个json对象数组
我有一个来自' https://randomuser.me/api/ '的对象数据我在我的项目中使用它。
I have an object "data" from 'https://randomuser.me/api/' which I'm using in my project.
{
"results": [
{
"gender": "female",
"name": {
"title": "miss",
"first": "mia",
"last": "sutton"
}
}
]
}
我从数据对象中解析结果如下; const {results} = data;
如何对我创建的结果变量进行结构化,并从中获取第一个项目我希望de-要声明为配置文件的结构化数组项。这表示我希望在我的应用程序中显示的API调用用户的配置文件数据。
I destructured results from the data object as follows;
const {results} = data;
How do I destructure the results variable I created, and obtain the first item from it I want the de-structured array item to be declared as profile. This represents the profile data for the user gotten from the API call that I want to display in my app.
你可以做它是这样的:
const { results: [firstItem] } = data;
参见这篇MDN文章有关解构的更多信息。
See this MDN article for more info on destructuring.
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);
根据你的代码(见评论) ,这也应该有效:
According to your code (see comments), this should work too:
const data = {
"results": [
{
"gender": "female",
"name": {
"title": "miss",
"first": "mia",
"last": "sutton"
}
}
]
};
const displayUserPhotoAndName = (data) => {
if(!data) return;
const { results } = data;
const { results: [profile] } = data;
console.log(profile);
}
displayUserPhotoAndName(data);