【问题标题】:how to destructure an array of objects in JavaScript如何在Javascript中解构一个json对象数组
【发布时间】:2019-08-05 04:11:06
【问题描述】:

我在我的项目中使用了来自“https://randomuser.me/api/”的对象“数据”。

{
  "results": [
    {
      "gender": "female",
      "name": {
        "title": "miss",
        "first": "mia",
        "last": "sutton"
      }
    }
  ]
}

我对数据对象的结果进行了如下解构; const {results} = data; 如何解构我创建的结果变量,并从中获取第一项我希望将解构的数组项声明为配置文件。这表示从 API 调用获得的用户的个人资料数据,我想在我的应用中显示。

【问题讨论】:

  • const {results: [{name: {title, first, last}}]} = data; 这将完全解构您列表中的第一项。
  • 谢谢。如果我想给数组中的第一个项目起个名字怎么样。例如myArray。所以当我登录myArray时,我应该得到; ` { "gender": "female", "name": { "title": "miss", "first": "mia", "last": "sutton" }`
  • @Gm Emmy,这是我在下面的回答,我举例说明如何解构数组中的第一项,如果需要,可以更深入
  • @GmEmmy Jo_va 给出了一些解构对象的示例。如果您只想将第一个元素放在变量中,只需使用 const {results: [firstPerson]} = data;
  • @Seblor firstPerson 是否代表数组项的新变量名?

标签: javascript arrays json ecmascript-6 destructuring


【解决方案1】:

你可以这样做:

const { results: [firstItem] } = data;

有关解构的更多信息,请参阅this MDN article

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

根据您的代码(参见 cmets),这也应该可以:

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;
  • 不,不是很遗憾。
  • ` const displayUserPhotoAndName = (data) => { if(!data) return;常量 {结果} = 数据; const {results: [profile]} = data;}` 我在一个接收data 作为参数的函数中执行此操作。
  • @Gm Emmy,您的错误一定在其他地方,该代码没有任何问题。我更新了答案并用你的代码添加了一个 sn-p 并且它可以工作
猜你喜欢
  • 2022-10-23
  • 1970-01-01
  • 2014-12-02
  • 1970-01-01
  • 1970-01-01
  • 2015-06-10
  • 2020-07-02
  • 1970-01-01
  • 2017-11-10
相关资源
最近更新 更多