如何在Javascript中构造一个json对象数组 [英] how to destructure a json array of objects in Javascript

查看:138
本文介绍了如何在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);

这篇关于如何在Javascript中构造一个json对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆