如何在JavaScript中解构对象数组

4
我在项目中使用了来自 'https://randomuser.me/api/'的 "data" 对象。
{
  "results": [
    {
      "gender": "female",
      "name": {
        "title": "miss",
        "first": "mia",
        "last": "sutton"
      }
    }
  ]
}

我从数据对象中解构了结果如下; const {results} = data; 我该如何解构我创建的results变量,并获取其中的第一个项?我希望这个解构出来的数组项被声明为profile,它代表了从 API 调用中获取的用户的配置文件数据,我想在我的应用程序中显示它。


2
const {results: [{name: {title, first, last}}]} = data; 这会完全解构您列表中的第一项。 - Seblor
1
谢谢。如果我想给数组中的第一个项目命名,怎么办呢?例如 myArray。因此,当我记录 myArray 时,我应该得到; { "gender": "female", "name": { "title": "miss", "first": "mia", "last": "sutton" } - Gm Emmy
1
@GmEmmy Jo_va 给出了一些解构对象的示例。如果你只想将第一个元素存储在变量中,可以简单地使用 const {results: [firstPerson]} = data; - Seblor
@Seblor,firstPerson 是否表示数组项的新变量名? - Gm Emmy
firstPerson 是一个任意的名称,它将保存列表中的第一个对象。您可以根据需要随意命名它。解构声明变量,命名由您决定。 - Seblor
显示剩余2条评论
1个回答

8

你可以这样做:

const { results: [firstItem] } = data;

想要了解更多有关解构赋值的信息,请查看此 MDN 文章

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);

根据您的代码(见注释),这也应该可以工作:

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);


@Gm Emmy,这个例子对你来说可行吗?const { results: [firstItem] } = data; - jo_va
不幸的是,它不是。 - Gm Emmy
const displayUserPhotoAndName = (data) => { if(!data) return; const {results} = data; const {results: [profile]} = data; }我正在一个接收"data"作为参数的函数中执行此操作。 - Gm Emmy
1
@Gm Emmy,你的错误肯定在别处,这段代码没有问题。我更新了答案并添加了一个片段,用你的代码它是可以运行的。 - jo_va

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接